我正试图使用dotenv webpack访问我的.env文件变量,以便稍后可以将它们捆绑在一起,并可以在我的网站上使用它们,但我遵循了说明并在网上查看了一遍,无法使其工作。
//.env
VAR=1234
// created a webpack.config.js with the following code
const Dotenv = require('dotenv-webpack');
module.exports = {
plugins: [
new Dotenv()
]
};
// index.js
console.log(process.env.VAR);
// undefined
我不知道该怎么办,因为我已经在下面的例子中学习了:https://github.com/mrsteele/dotenv-webpack看起来应该很容易。。。
正如Pandhu Wibowo所建议的,请对他竖起大拇指,我使用了webpack-cli、webpack和dotenv软件包使其工作。如何将.env文件变量传递到webpack配置?
./env
VAR=1234
./webpack.config.js
const webpack = require('webpack');
// replace accordingly './.env' with the path of your .env file
require('dotenv').config({ path: './.env' });
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
plugins: [
new webpack.DefinePlugin({
"process.env": JSON.stringify(process.env)
}),
]
};
./package.json
"scripts": {
"start": "webpack"
},
npm run start
--> creates the bundle.js which will include the env variable
为什么不使用dotenv
包?
dotenv
如果您想使用dotenv-webpack
包来定义环境文件,您需要告诉它您的.env文件在哪里,下面是我所做的:
webpack.dev.js
- 导入:
const Dotenv = require('dotenv-webpack');
- 在插件数组中使用它,并将
.env.developement
路径传递给它:
plugins: [
...,
new Dotenv({
path: `${environmentsPath}/.env.development`,
systemvars: true, //Set to true if you would rather load all system variables as well (useful for CI purposes)
}),
],
webpack.prod.js
- 导入:
const Dotenv = require('dotenv-webpack');
- 在插件数组中使用它,并将
.env
路径传递给它:
plugins: [
...,
new Dotenv({
path: `${environmentsPath}/.env`,
systemvars: true, //Set to true if you would rather load all system variables as well (useful for CI purposes)
}),
],
我喜欢这种方法的好处是,您可以使用env-cmd
包(例如:"build:staging": "env-cmd -f environments/.env.staging webpack --config buildTools/webpack.prod.js --progress --color"
(覆盖环境文件
如果有帮助,请告诉我。
这是我的补充点:
要从客户端应用程序访问环境变量,它们必须前缀为REACT_APP_。否则,只能在服务器端。
所以我的.env文件看起来像
REACT_APP_API_KEY=my-api-key
REACT_APP_SECRET=secretInfo2
在以下人员的帮助下:https://jasonwatmore.com/post/2022/06/22/react-access-environment-variables-from-dotenv-env
新的webpack。环境插件({NODE_ENV:"开发",//除非定义了process.ENV.NODE_ENV,否则使用"开发"DEBUG:false,});
https://webpack.js.org/plugins/environment-plugin/
我只是在开发过程中尝试访问我的.env变量,甚至还没有构建我的应用程序,并且无法通过使用dot-env-webpack或DefinePlugin的其他方法访问任何变量。这种方式对我来说很成功。