繁体   English   中英

无法使用 dotenv-webpack 访问 process.env 变量

[英]Unable to access process.env variables with dotenv-webpack

我正在尝试使用 dotenv-webpack 访问 my.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看起来应该很容易...

为什么不使用dotenv package?

dotenv

正如 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-webpack package 来定义环境文件,您需要告诉它您的.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 package 覆盖环境文件(例如: "build:staging": "env-cmd -f environments/.env.staging webpack --config buildTools/webpack.prod.js --progress --color" )

如果有帮助,请告诉我。

这对我来说是补充点:

要从客户端应用程序访问环境变量,它们必须以 REACT_APP_ 为前缀。 否则它们只能在服务器端访问。

所以 my.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM