Angshuman Agarwal
Angshuman Agarwal

Reputation: 4866

Typescript / Webpack check if running via Production config

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 ?

Upvotes: 4

Views: 2493

Answers (1)

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 :-)

Upvotes: 2

Related Questions