How to turn on/off ReactJS 'development mode'?

后端 未结 7 1296
独厮守ぢ
独厮守ぢ 2020-11-29 17:38

Started using ReactJS\'s prop validation feature, which as the docs say only works in \'development mode\' for performance reasons.

React seems to be validating the

7条回答
  •  难免孤独
    2020-11-29 18:21

    The other answer assumes you are using external pre-built files from react, and while correct that is not how most folks are going to or should consume React as a package. Moreover, at this point most every React library and package also relies on the same convention to toggle dev time helpers off during production. Just using the minified react will leave all those potential optimizations on the table as well.

    Ultimately the magic comes down to React embedding references to process.env.NODE_ENV throughout the codebase; these act like a feature toggle.

    if (process.env.NODE_ENV !== "production")
      // do propType checks
    

    The above is the most common pattern, and other libraries follow it as well. So to "disable" these checks we need to toggle NODE_ENV to "production"

    The proper way to disable "dev mode" is through your bundler of choice.

    webpack

    Use the DefinePlugin in your webpack config like so:

    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify("production")
    })
    

    Browserify

    Use the Envify transform and run your browserify build step with NODE_ENV=production ("set NODE_ENV=production" on Windows)

    Result

    This will produce output bundles that has all instances of process.env.NODE_ENV replaced with the string literal: "production"

    Bonus

    When minifying the transformed code you can take advantage of "Dead Code Elimination". DCE is when the minifier is smart enough to realize that: "production" !== "production" is always false and so will just remove any code in the if block saving you bytes.

提交回复
热议问题