How to set React to production mode when using Gulp

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

    2017 - Edit: anyone trying to set up React in Gulp for a new project: Just use create-react-app


    Step I: Add the following to your gulpfile.js somewhere

    gulp.task('apply-prod-environment', function() {
        process.env.NODE_ENV = 'production';
    });
    

    Step II: Add it to your default task (or whichever task you use to serve/build your app)

    // before: 
    // gulp.task('default',['browsersync','watch'], function() {});
    // after:
       gulp.task('default',['apply-prod-environment', 'browsersync','watch'], function() {});
    

    OPTIONAL: If you want to be ABSOLUTELY CERTAIN that you are in prod mode, you can create the following slightly enhanced task instead of the one in Step I:

    gulp.task('apply-prod-environment', function() {
        process.stdout.write("Setting NODE_ENV to 'production'" + "\n");
        process.env.NODE_ENV = 'production';
        if (process.env.NODE_ENV != 'production') {
            throw new Error("Failed to set NODE_ENV to production!!!!");
        } else {
            process.stdout.write("Successfully set NODE_ENV to production" + "\n");
        }
    });
    

    Which will throw the following error if NODE_ENV is ever not set to 'production'

    [13:55:24] Starting 'apply-prod-environment'...
    [13:55:24] 'apply-prod-environment' errored after 77 μs
    [13:55:24] Error: Failed to set NODE_ENV to production!!!!
    

提交回复
热议问题