ana*_*477 7 reactjs webpack webpack-dev-server
我想从我的 .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);
...
}
}
Run Code Online (Sandbox Code Playgroud)
这打印:
NODE_ENV 开发
REACT_APP_MYAPP
undefined
在我的 package.json 中有:
"scripts":{
"start" : "webpack-dev-server --config webpack.dev.js",
"build" : "webpack --config webpack.prod.js"
}
Run Code Online (Sandbox Code Playgroud)
在我的 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"
});
Run Code Online (Sandbox Code Playgroud)
我把我的 .env 文件放在我项目的根目录下,在 webpack.dev.js 和 package.json 旁边:
REACT_APP_MYAPP= http://localhost:8080/
所以我认为,在文件中获取变量并不成功。
请问如何获取代码中的REACT_APP_MYAPP值?
Jai*_*Jai 11
穿过又深又黑的兔子洞,你会发现以下事实:
process或其他 Node.js 变量。DefinePlugin需要重新定义。DefinePlugin必须是字符串化的,即使它们是字符串。EnvironmentPlugin 考虑到 Webpack 5,这让事情变得更加混乱。process.env 不是你应该在前端使用的东西。process并重新添加其他人,但它不再可用是有原因的。process.env是全局访问变量。但它是乘坐错误航班的乘客。我们可以删除它,而是直接访问预期的变量:plugins: [
new DefinePlugin({
// With dotenv (values must be stringified)
...Object.entries(dotenv.config().parsed).reduce((acc, curr) => ({...acc, [`${curr[0]}`]: JSON.stringify(curr[1]) }), {}),
// Without dotenv
'myString': JSON.stringify('IAmAString')
})
]
Run Code Online (Sandbox Code Playgroud)
在前端:
declare var myString: string;
console.log(myString); // 'IAmAString'
Run Code Online (Sandbox Code Playgroud)
如果您有多个带有变量的对象,那么抽象字符串化是有意义的:
// Create a function to stringify values
function stringifyValues(object: {[key: string]: any;}){
return Object.entries(object).reduce((acc, curr) => ({...acc, [`${curr[0]}`]: JSON.stringify(curr[1]) }), {} as { [key: string]: string; });
}
// use with DefinePlugin
plugins: [
new DefinePlugin({
...stringifyValues(dotenv.config().parsed),
...stringifyValues(dotenv.config({ path: '/.env.special' }).parsed),
'myObject': stringifyValues({
name: 'Object',
description: 'to be an object'
})
})
]
Run Code Online (Sandbox Code Playgroud)
如果你真的想访问process.env:
plugins: [
new DefinePlugin({
// this might expose confidential data about your environment
'process.env': JSON.stringify(process.env),
// the correct way
'process.env.USERNAME': JSON.stringify('Donald Hump')
})
]
Run Code Online (Sandbox Code Playgroud)
在前端:
declare var process: any;
console.log(process) // will NOT work, because process hasn't been injected
console.log(process.env); // will work but risky
console.log(process.env.USERNAME); // correct: 'Donald Hump'
Run Code Online (Sandbox Code Playgroud)
通过在启动中添加 REACT_APP_MYAPP 的第一个解决方案不起作用。但第二个解决方案有效。
解决方案:
在 my 中添加require('dotenv').config()文件webpack.dev.js并替换:
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify("development"),
"process.env.REACT_APP_MYAPP": JSON.stringify(process.env.REACT_APP_MYAPP)
})
Run Code Online (Sandbox Code Playgroud)
和
new webpack.EnvironmentPlugin(['NODE_ENV', 'REACT_APP_MYAPP']);
Run Code Online (Sandbox Code Playgroud)
谢谢你!
| 归档时间: |
|
| 查看次数: |
9695 次 |
| 最近记录: |