How to set React to production mode when using Gulp

后端 未结 5 1813
盖世英雄少女心
盖世英雄少女心 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 20:54

    Similar to the other answers, but hopefully gives someone a starting point:

    var vendorList = ['react', 'react-dom'];
    
    gulp.task('vendor-dev', function() {
        browserify()
            .require(vendorList)
            .bundle()
            .on('error', handleErrors)
            .pipe(source('vendor.js'))
            .pipe(gulp.dest('./build/dev/js'));
    });
    
    gulp.task('vendor-production', function() {
        process.env.NODE_ENV = 'production';
        browserify()
            .require(vendorList)
            .bundle()
            .on('error', handleErrors)
            .pipe(source('vendor.js'))
            .pipe(buffer())
            .pipe(uglify({ mangle: false }))
            .pipe(gulp.dest('./build/production/js'));
    });
    

    The main difference is I am explicitly setting the NODE_ENV prior to bundling the vendor libraries. Gulp tasks aren't guaranteed to run in order.

    Am I running in production mode?

    If you remove the uglify line (and prior buffer) you will notice that both the dev and production builds are near identical in size - and match in line count.

    The difference is the production version will be littered with:

    "production" !== "production" ? [show dev error] : [no nothing]
    

    Most reputable minify'ers (I believe) will strip out deadend code, such as the above, which will always result in false.

    But really how do I tell?

    Easiest method to be sure, would be goto the console of your running application and type:

    React.createClass.toString();
    

    The output should be:

    "function (e){var t=function(e,t,n){this.__reactAutoBindMap&&c(this),"[....and more and more]
    

    If you find the createClass in the react source, you will see:

    createClass: function (spec) {
        var Constructor = function (props, context, updater) {
          // This constructor is overridden by mocks. The argument is used
          // by mocks to assert on what gets mounted.
    
          if ("production" !== 'production') {
            "production" !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: react-legacyfactory') : undefined;
          }
    
          // Wire up auto-binding
          if (this.__reactAutoBindMap) {
            bindAutoBindMethods(this);
          }
    

    Notice how the console output skips straight through to this.__reactAutobind, because you are running in production mode, and using an minify'er, all the !== 'production' warngins and checks have been skipped over.

提交回复
热议问题