dotenv-webpack 在 webpack.config.js 中使用环境变量 [英] dotenv-webpack use environment variable in webpack.config.js

查看:187
本文介绍了dotenv-webpack 在 webpack.config.js 中使用环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的.env是这样设置的:

SECRET_KEY=mysecretkey123

我的webpack.config.js是这样设置的:

const Dotenv = require('dotenv-webpack');

module.exports = {
...
proxy: {
 'api': {
   target: 'foo.bar'
   headers: {'api_token': process.env.SECRET_KEY}
  }
}
...
plugins: [
    new Dotenv({
      path: '.env',
    }),
]

}

但是,当我运行我的应用程序时,我收到一条错误消息,指出我的 api 令牌是 undefined

However when I run my app I get an error saying that my api token is undefined

我知道 dotenv 工作正常,因为在我的应用程序本身中,我可以执行 console.log(process.env.SECRET_KEY) 并查看我的密钥,但是这似乎不会暴露我的环境我的 webpack.config.js 文件本身中的变量.

I know dotenv is working properly, because within my application itself I can do console.log(process.env.SECRET_KEY) and see my secret key, however it appears this does not expose my environment variables within my webpack.config.js file itself.

有没有办法配置 dotenv-webpack 以允许在 webpack.config.js 中使用环境变量?

Is there a way to configure dotenv-webpack to allow the use of environment variables within the webpack.config.js?

推荐答案

如果您想直接在 webpack.config.js 中使用 .env 文件中的变量,请了解它在运行时的行为与任何其他 javascript 文件一样,所以你需要直接在配置文件中使用 dotenv 包,而不是 dotenv-webpack 插件,它将变量插入到您的捆绑代码中.

If you want to use variables from your .env file in the webpack.config.js directly, understand that it behaves just as any other javascript file while being run, so you need to use the dotenv package directly in the config file, not the dotenv-webpack plugin, which inserts the variables into your bundled code.

即,只需 npm install dotenv 并将 require('dotenv').config() 添加到 webpack.config 文件的顶部.

I.e, just npm install dotenv and add require('dotenv').config() to the top of your webpack.config file.

这篇关于dotenv-webpack 在 webpack.config.js 中使用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆