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

时间:2022-02-10 16:08:05

Webpack's DefinePlugin is not passing through environment variables. I'm using Webpack v2.2.1

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

My Webpack plugins block is below:

我的Webpack插件块如下:

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()
 ]

server.js:

server.js:

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

.babelrc configuration:

.babelrc配置:

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

I've switched up the babel presets, reverted Webpack to 2.0.0, and really don't see what could be causing these variables not to be copied over. If I need to supply any additional info or code, lmk. :)

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

1 个解决方案

#1


1  

Hope this is still helpful to someone out there.

希望这对那里的人有用。

Webpack makes static bundle file(s), so environment variables have to be available at the time webpack does its thing.

Webpack制作静态捆绑文件,因此webpack做的时候必须有环境变量。

Based on the .babelrc file, I can see it's a react app bundled with webpack. So what you want to do is install dotenv as a dependency npm install --save dotenv

基于.babelrc文件,我可以看到它是与webpack捆绑在一起的反应应用程序。所以你想要做的是安装dotenv作为依赖npm install --save dotenv

In your webpack.config.js file, you need to do the following:

在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;

So what happens is at bundle time, the environment variables are stored globally into the process.env object created in the newly defined webpack plugin, and this makes our variables accessible anywhere within our codebase via process.env.[VARIABLE_NAME]

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

P.S: On cloud servers such as heroku, make sure to set all desired environment variables before deploying your code. And if changes are made after code deploy, you need to re-deploy for webpack to update the stored variables. This method works with both react and angular. I believe it should work with all webpack builds. Edit: Also, we have to do a JSON.stringify() on the environment variable(s) we are passing into the webpack plugin.

P.S:在诸如heroku之类的云服务器上,确保在部署代码之前设置所有需要的环境变量。如果在代码部署后进行更改,则需要重新部署webpack以更新存储的变量。这种方法适用于反应和角度。我相信它应该适用于所有webpack构建。编辑:另外,我们必须对传递给webpack插件的环境变量执行JSON.stringify()。

#1


1  

Hope this is still helpful to someone out there.

希望这对那里的人有用。

Webpack makes static bundle file(s), so environment variables have to be available at the time webpack does its thing.

Webpack制作静态捆绑文件,因此webpack做的时候必须有环境变量。

Based on the .babelrc file, I can see it's a react app bundled with webpack. So what you want to do is install dotenv as a dependency npm install --save dotenv

基于.babelrc文件,我可以看到它是与webpack捆绑在一起的反应应用程序。所以你想要做的是安装dotenv作为依赖npm install --save dotenv

In your webpack.config.js file, you need to do the following:

在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;

So what happens is at bundle time, the environment variables are stored globally into the process.env object created in the newly defined webpack plugin, and this makes our variables accessible anywhere within our codebase via process.env.[VARIABLE_NAME]

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

P.S: On cloud servers such as heroku, make sure to set all desired environment variables before deploying your code. And if changes are made after code deploy, you need to re-deploy for webpack to update the stored variables. This method works with both react and angular. I believe it should work with all webpack builds. Edit: Also, we have to do a JSON.stringify() on the environment variable(s) we are passing into the webpack plugin.

P.S:在诸如heroku之类的云服务器上,确保在部署代码之前设置所有需要的环境变量。如果在代码部署后进行更改,则需要重新部署webpack以更新存储的变量。这种方法适用于反应和角度。我相信它应该适用于所有webpack构建。编辑:另外,我们必须对传递给webpack插件的环境变量执行JSON.stringify()。