Typescript / Webpack check if running via Production config

梦想的初衷 提交于 2021-02-17 02:08:54

问题


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:


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



来源:https://stackoverflow.com/questions/49639143/typescript-webpack-check-if-running-via-production-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!