如何将 .env 文件变量传递给 webpack 配置? [英] How to pass .env file variables to webpack config?

查看:42
本文介绍了如何将 .env 文件变量传递给 webpack 配置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 webpack 的新手,几乎完成了所有构建部分,但现在的问题是我想将 .env 文件中的环境变量传递给 webpack 配置,以便我可以通过以下方式将该变量传递给我的构建文件webpack.DefinePlugin 插件.

I am new to webpack and worked out almost all build sections, but now the problem is that I want to pass the environment variables from a .env file to webpack config, so that I can pass that variables to my build files via webpack.DefinePlugin plugin.

目前我能够将环境变量直接从 webpack 传递到我的构建.请参阅下面我在 webpack 中使用的代码.

Currently I am able to to pass environment variable directly from webpack to to my build. Please see the code below which I used in webpack.

new webpack.DefinePlugin({
            "API_URL": JSON.stringify("http://my-api.com"),
            "FRONT_END_API_KEY" : "MYFRONTENDKEYGOESHERE"
        }),

我的 package.json 构建脚本是

"scripts": {
    "start": "NODE_ENV=development webpack-dev-server --progress --port 8000 --content-base app/build/src"
    } 

推荐答案

您可以使用 dotenv 包这个目的.

You can use dotenv package for this purpose.

安装软件包后,在配置顶部添加:

After installing the package, add this in the top of your config:

const webpack = require('webpack'); // only add this if you don't have yet

// replace accordingly './.env' with the path of your .env file 
require('dotenv').config({ path: './.env' }); 

然后在 plugins 部分,添加:

then in plugins section, add this:

new webpack.DefinePlugin({
  "process.env": JSON.stringify(process.env);
}),

这篇关于如何将 .env 文件变量传递给 webpack 配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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