React and Grunt - Envify NODE_ENV='production' and UglifyJS

前端 未结 3 1952
猫巷女王i
猫巷女王i 2021-02-15 17:19

I am using Grunt to build a React project and I want to have \'dev\' and \'prod\' flavours. As react docs says:

To use React in productio

相关标签:
3条回答
  • 2021-02-15 18:02

    Just an addition to the great answer by FakeRainBrigand, if you're running on Windows (like me) then you need a subtly different syntax in your scripts section:

    {
      "scripts": {
        "build": "SET NODE_ENV=development&&grunt build-dev",
        "dist": "SET NODE_ENV=production&&grunt dist"
      }
    },
    "devDependencies": {
      "grunt": "...",
      "grunt-cli": "..."
    }
    
    0 讨论(0)
  • 2021-02-15 18:05

    Both John Reilly's and FakeRainBrigand 's answers did not work for me. What worked for me was the following:

    Step 1 - Run this command where your package.json is

    npm i grunt-env --save-dev
    

    Step 2 - Add the code in "evn:" to your Gruntfile.js within grunt.initConfig like so:

    grunt.initConfig({
    
    ...
    
    env: {
        prod: {
            NODE_ENV: 'production'
        }
    },
    
    ...
    
    });
    

    Step 3 - Add the grunt task to your Gruntfile.js

    grunt.loadNpmTasks('grunt-env');
    

    Step 4 - Call it before browserify like so:

    grunt.registerTask("default", ["env", "browserify"]);
    
    0 讨论(0)
  • 2021-02-15 18:14

    Transforms are local, and well made packages put their transforms in their package.json file. Unless you're using envify in your own code, you don't need to do anything with it.

    What you do need is grunt-env, or another way to set environmental variables.

    Here's an alternative by using package.json:

    {
      "scripts": {
        "build": "NODE_ENV=development grunt build-dev",
        "dist": "NODE_ENV=production grunt dist"
      }
    },
    "devDependencies": {
      "grunt": "...",
      "grunt-cli": "..."
    }
    

    The benefit here is that the person using your package doesn't even need to install grunt globally. npm run build will run ./node_modules/.bin/grunt build-dev with the correct environmental variable set.

    0 讨论(0)
提交回复
热议问题