Webpack DefinePlugin不将环境变量传递给节点服务器

Bra*_*ady 9 node.js webpack

Webpack DefinePlugin不是通过环境变量.我正在使用Webpackv2.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()
 ]
Run Code Online (Sandbox Code Playgroud)

server.js:

console.log('env', process.env.NODE_ENV) // undefined
console.log('url', process.env.API_URL); // undefined
Run Code Online (Sandbox Code Playgroud)

.babelrc 组态:

{"presets": ["es2015", "stage-0", "react"]}
Run Code Online (Sandbox Code Playgroud)

我已经开启了babel预设,将Webpack恢复到2.0.0,并且真的看不出可能导致这些变量无法复制的原因.如果我需要提供任何其他信息或代码,请使用lmk.:)

小智 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;
Run Code Online (Sandbox Code Playgroud)

因此,在捆绑时发生的情况是,环境变量全局存储到process.env新定义的 webpack 插件中创建的对象中,这使得我们的变量可以通过以下方式在代码库中的任何位置访问:process.env.[VARIABLE_NAME]

PS:在 Heroku 等云服务器上,请确保在部署代码之前设置所有所需的环境变量。如果代码部署后发生更改,则需要重新部署 webpack 以更新存储的变量。此方法适用于 React 和 Angular。我相信它应该适用于所有 webpack 构建。编辑:另外,我们必须对JSON.stringify()传递到 webpack 插件的环境变量进行操作。