Search code examples
node.jsreactjswebpackcreate-react-app

create react app cannot read environment variable after build


I have a react app , created with create-react-app then I build the app with command: npm run build

It's using serve to run the app after build, if we start the app with development code by running ENV=production npm run start it can read the process.env.ENV variable beacause I'm adding this plugins to webpack dev config

   new webpack.DefinePlugin({
      'process.env':{
        'ENV': JSON.stringify(process.env.ENV),
      }
    }),

I also add the script above to webpack prod config, but if I try this command after build ENV=prod serve -s build, it cannot read the environment variable

How to fix this?


Solution

  • The reason why you can not read the ENV var is because:

    (1) In development mode webpack watches your files and bundles you app on the fly. It also will read (because of the DefinePlugin) your process.env.ENV and will add it as a global variable. So it is basically piping variables from process.env to your JS app.

    (2) After you've build your app (with webpack) everything is already bundled up into one or more files. When you run serve you just start a HTTP server that serves the static build files. So there is no way to pipe the ENV to you app.

    Basically what the DefinePlugin does is add a var to the bundle. E.g.

    new webpack.DefinePlugin({
      'token': '12356234ga5q3aesd'
    })
    

    will add a line similar to this:

    var token = '12356234ga5q3aesd';
    

    since the JS files is static there is no way to change this variable after you've build/bundled it with webpack. Basically, when you do npm run build you're creating the compiled binary/.dll/.jar/... file and can no longer influence its contents via the plugin.