我正在尝试使用 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 包使其工作。 How to pass .env file variables to webpack config?
./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
关于javascript - 无法使用 dotenv-webpack 访问 process.env 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70716490/