2

I am using webpack, reactjs, typescript. In my .tsx code, I have a requirement where I need to route to URL depending upon my environment i.e. Production or Development. So, how can I check for the environment and load the correct URL dynamically ?

Angshuman Agarwal
  • 4,796
  • 7
  • 41
  • 89

1 Answers1

2

You can add a plugin to define an environment variable that can be accessed within the code, like this:

new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify('production')
})

And then inside your code you just have to check for process.env.NODE_ENV.

Needless to say that you can manage the plugin with an environment variable that you can pass via cli, like this:

webpack --env.production

And then have your webpack.config.js with something like this:

module.exports = function(env) {
    return {
        /*[...]*/
        plugins: [new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(env.production ? 'production' : 'development')
        })]
        /*[...]*/
    };
};

Source: That's how react works :-)

Jorge Fuentes González
  • 11,568
  • 4
  • 44
  • 64
  • Thanks - will give a shot at it. My understanding is since the NODE_ENV environment variable and the corresponding process.env.NODE_ENV runtime field are strictly Node-specific concepts, by default that value does not exist in client-side code. Looks like DefinePlugin is forcing that to be a global variable ? – Angshuman Agarwal Apr 03 '18 at 21:58
  • @AngshumanAgarwal Exactly, `DefinePlugin` makes that inside any webpack bundle code running in any environment will have the defined variable. – Jorge Fuentes González Apr 03 '18 at 22:00
  • Hope `UglifyJS` does not strip that out as a dead code brach during minification because it will encounter `if("production" !== "production")` where `process.env.NODE_ENV = "production"` -- as being set from the cli during the build process. – Angshuman Agarwal Apr 03 '18 at 22:05
  • @AngshumanAgarwal There's no problem with that, as if the branch is never reached, you don't need the code inside it. Is actually good to strip it to reduce bundle size. – Jorge Fuentes González Apr 03 '18 at 23:03
  • import using "require" worked for me: `new (require('webpack')).DefinePlugin({ ...` – Rodrigo João Bertotti Oct 09 '20 at 15:16