Change hard coded url constants for different environments via webpack

前端 未结 2 441
情歌与酒
情歌与酒 2020-12-24 11:28

I have a ApiCaller.js module which generate calls to our api server to get data. It has const field API_URL which points to server url. This

2条回答
  •  情深已故
    2020-12-24 12:10

    You could set the define plugin to define a PRODUCTION variable as follows (or alternatively to true if you use different configuration files for the builds):

    new webpack.DefinePlugin({
        PRODUCTION: process.env.NODE_ENV === 'production'
    })
    

    Then in your code you will write something like:

    var API_URL = PRODUCTION ? 'my-production-url' : 'my-development-url';
    

    During compilation webpack will replace PRODUCTION with its value (so either true or false), and this should allow UglifyJS to minify our expression:

    var API_URL =  ? 'my-production-url' : 'my-development-url';
    

    The worst case scenario is uglify not being able to minify the conditional expression leaving it as is.

提交回复
热议问题