我希望能从我的.env文件中获取变量,但我总是得到undefined
。
这是我的js代码:
require('dotenv').config();
class Header extends React.Component{
constructor(props){...}
render(){
console.log("NODE ENV", process.env.NODE_ENV);
console.log("REACT_APP_MYAPP", process.env.REACT_APP_MYAPP);
...
}
}
这将打印:
NODE_ENV development
REACT_APP_MYAPP
undefined
在我的package.json文件中有:
"scripts":{
"start" : "webpack-dev-server --config webpack.dev.js",
"build" : "webpack --config webpack.prod.js"
}
而在我的webpack.dev.js文件中:
const webpack = require("webpack");
const merge = require("webpack-merge");
const path = require("path");
const common = require("./webpack.common.js");
module.exports = merge.smart(common, {
devServer: {
contentBase: path.resolve(__dirname, "dist"),
hot: true,
overlay: {
warnings: true,
errors: true
},
inline :true,
historyApiFallback: true,
port: 8085
},
devtool: "inline-sourcemap",
optimization: {
namedModules: true
},
plugins: [
new webpack.HotModulReplacementPlugin(),
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify("development"),
"process.env.REACT_APP_MYAPP": JSON.stringify(process.env.REACT_APP_MYAPP)
})
],
mode: "development"
});
我把我的.env文件放在项目根目录下,与webpack.dev.js和package.json并列:
REACT_APP_MYAPP=http://localhost:8080/
所以我认为,它没有成功获取文件中的变量。
请问我如何在代码中获取REACT_APP_MYAPP的值?