Node.js 在npm脚本中导出.env文件
我正在尝试在我的react应用程序中进行一些测试,我需要导出我的.env文件。 我不能使用dotenv,因为它不能在react中缩小 我想在测试脚本中添加.env文件。比如: 测试:'export.env mocha…“如果您正在使用,您可以这样做Node.js 在npm脚本中导出.env文件,node.js,reactjs,mocha.js,Node.js,Reactjs,Mocha.js,我正在尝试在我的react应用程序中进行一些测试,我需要导出我的.env文件。 我不能使用dotenv,因为它不能在react中缩小 我想在测试脚本中添加.env文件。比如: 测试:'export.env mocha…“如果您正在使用,您可以这样做 node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/your/env/vars 如果不指定.env文件的路径,它将从项目根目录中读取。另一种方法是,在不使用
node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/your/env/vars
如果不指定.env文件的路径,它将从项目根目录中读取。另一种方法是,在不使用任何附加库的情况下,创建一个JS文件,将具有典型节点环境的对象导出为属性。然后导入此文件并根据当前进程设置变量。env.Node\u env。明显的缺点是您在磁盘上存储了一个可访问的文件,该文件可能包含敏感数据 例如: env/config.js
export default {
"development": {
name: "Bob"
},
"production": {
name: "Jim"
},
"staging": {
name: "Alexa"
},
"test": {
name: "Nancy"
}
};
import React from "react";
import ReactDOM from "react-dom";
import config from "./env/config";
import "./styles.css";
const env = process.env.NODE_ENV;
const name = config[env].name;
function App() {
return (
<div className="App">
<h1>Current ENV: {env}</h1>
<h2>Current Name: {name}</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
example.js
export default {
"development": {
name: "Bob"
},
"production": {
name: "Jim"
},
"staging": {
name: "Alexa"
},
"test": {
name: "Nancy"
}
};
import React from "react";
import ReactDOM from "react-dom";
import config from "./env/config";
import "./styles.css";
const env = process.env.NODE_ENV;
const name = config[env].name;
function App() {
return (
<div className="App">
<h1>Current ENV: {env}</h1>
<h2>Current Name: {name}</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
从“React”导入React;
从“react dom”导入react dom;
从“/env/config”导入配置;
导入“/styles.css”;
const env=process.env.NODE_env;
const name=config[env].name;
函数App(){
返回(
当前环境:{ENV}
当前名称:{Name}
);
}
const rootElement=document.getElementById(“根”);
render(,rootElement);
那么,如果我在使用mocha,我该怎么做?我必须在js文件中创建mocha脚本并执行它?@SaitoHs只需将示例脚本中的“节点”替换为“mocha”。