Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack DefinePlugin not passing environment variables to node server

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

My Webpack plugins block is below:

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:

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

.babelrc configuration:

{"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. :)

like image 384
Brady Avatar asked Feb 04 '17 00:02

Brady


People also ask

How does webpack DefinePlugin work?

The DefinePlugin replaces variables in your code with other values or expressions at compile time. This can be useful for allowing different behavior between development builds and production builds.

What is webpack DefinePlugin?

Oct 29, 2021. Webpack's DefinePlugin() function lets you replace a given token in the compiled code with another token. A common use case is using it to define environment variables when you cannot use an . env file directly.

What is process env Node_env?

NODE_ENV is an environment variable that stands for node environment in express server. The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production).


1 Answers

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.

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

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

    //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]

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.

like image 193
saheedt Avatar answered Sep 28 '22 06:09

saheedt