Webpack DefinePlugin未将环境变量传递给node服务器

11

Webpack的DefinePlugin没有传递环境变量。我正在使用Webpack v2.2.1

我的Webpack plugins块如下:

plugins: [
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify("development"),
    'process.env.API_URL': JSON.stringify("test")
  }),
  new webpack.optimize.OccurrenceOrderPlugin(),
  new webpack.HotModuleReplacementPlugin(),
  new webpack.NoEmitOnErrorsPlugin()
 ]

服务器.js:

console.log('env', process.env.NODE_ENV) // undefined
console.log('url', process.env.API_URL); // undefined

.babelrc 配置:

{"presets": ["es2015", "stage-0", "react"]}

我已经更改了 babel 预设,将 Webpack 恢复到 2.0.0,并且真的不知道可能导致这些变量未被复制的原因。如果需要提供任何其他信息或代码,请告诉我。


我看不出这个不工作的原因。 - cgatian
1
很高兴知道我不太疯狂 XD - Brady
使用 console.log() 将你的 webpack 输出到控制台,以确保没有其他东西覆盖它。(如果你正在合并多个配置) - cgatian
2
有进展吗?我也遇到了同样的 bug。 - Mike
1个回答

3
希望这对某些人仍然有所帮助。
Webpack 生成静态捆绑文件,因此环境变量必须在 webpack 运行时可用。
根据 .babelrc 文件,我可以看出它是一个使用 webpack 捆绑的 react 应用程序。 所以你需要安装 dotenv 作为依赖项 npm install --save dotenv 在你的 webpack.config.js 文件中,你需要执行以下操作:
    //require dotenv and optionally pass path/to/.env
    const DotEnv = require('dotenv').config({path: __dirname + '/.env'}),
          webpack = require('webpack'),

   //Then define a new webpack plugin which reads the .env variables at bundle time
          dotEnv = new webpack.DefinePlugin({
              "process.env": {
              'BASE_URL': JSON.stringify(process.env.BASE_URL),
              'PORT': JSON.stringify(process.env.PORT)
             }
        });

    // Then add the newly defined plugin into the plugin section of the exported
    //config object
    const config = {
        entry: `${SRC_DIR}/path/to/index.js`,
        output: {
            path: `${DIST_DIR}/app`,
            filename: 'bundle.js',
            publicPath: '/app/'
        },
        module: {
            loaders: [
                {
                    test: /\.js?$/,
                    include: SRC_DIR,
                    loader: "babel-loader",
                    exclude: /node_modules/,
                    query: {
                        presets: ["react", "es2015", "stage-3"]
                    }
                }
            ]
        },
        plugins: [
            dotEnv
        ]
    };
    module.exports = config;

所发生的事情是在打包过程中,环境变量被全局存储到新定义的webpack插件所创建的process.env对象中, 这使得我们能够通过process.env.[VARIABLE_NAME]在代码库的任何地方访问变量。
P.S: 在像Heroku这样的云服务器上,请确保在部署代码之前设置所有所需的环境变量。如果在代码部署后进行更改,则需要重新部署以便Webpack更新存储的变量。 此方法适用于React和Angular。我相信它应该适用于所有Webpack构建。 另外,我们必须对传递到Webpack插件中的环境变量进行JSON.stringify()处理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接