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 ?
1 Answer
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 :-)
5 Comments
Angshuman Agarwal
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 ?
Jorge Fuentes González
@AngshumanAgarwal Exactly,
DefinePlugin makes that inside any webpack bundle code running in any environment will have the defined variable.Angshuman Agarwal
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.Jorge Fuentes González
@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.
Rodrigo João Bertotti
import using "require" worked for me:
new (require('webpack')).DefinePlugin({ ...
dynamicallyi.e. during actual code execution ? Config is only used during thebuild process. Could you please elaborate with a sample if possible ?webpackhas nicely documented it too - webpack.js.org/guides/production