How to set React to production mode when using Gulp

后端 未结 5 1810
盖世英雄少女心
盖世英雄少女心 2021-02-03 20:36

I need to run React in production mode, which presumably entails defining the following somewhere in the enviornment:

process.env.NODE_ENV = \'production\';
         


        
5条回答
  •  鱼传尺愫
    2021-02-03 21:00

    Unfortunately none of the above answers work, because setting process.env.NODE_ENV has no effect in Browserify. The resulting bundle still has process.env.NODE_ENV references in it and hence

    • Browserify will not require() the React production version modules,
    • the minifier will not be able to remove dead code, and
    • the application will still be running in debug mode.

    This is unfortunately not the only place where this approach is offered as the correct answer :-(


    The correct approach can be found in e.g.

    • https://github.com/hughsk/envify/issues/15#issuecomment-62229101
    • https://reactjs.org/docs/optimizing-performance.html#browserify

    You need to switch the envify transform to be a global one, e.g.

    # note the "-g" instead of the usual "-t"
    $ browserify ... -g [ envify --NODE_ENV production ] ....
    

    or in gulpfile.js

    browserify(...)
        ...
        .transform('envify', {
            global:   true, // also apply to node_modules
            NODE_ENV: debug ? 'development' : 'production',
        })
        ...
        .bundle()
        ...
        .pipe(gulpif(!debug, babelMinify())) // my example uses gulp-babel-minify
        ...
    

提交回复
热议问题