如何打开/关闭ReactJS的“开发模式”?

reactjs React.js

Jim老丝梅

2020-03-12

从使用ReactJS的prop验证功能开始,正如文档所说,出于性能原因,该功能仅在“开发模式”下有效。

React似乎正在验证我注释过的特定组件的属性,但我不记得显式打开“开发模式”。

我尝试搜索如何触发/切换开发模式,但没有任何运气。

第865篇《如何打开/关闭ReactJS的“开发模式”?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
AL村村 2020.03.12

另一个答案是假设您使用的是来自React的外部预构建文件,而正确的做法不是大多数人打算或应该将 React作为软件包使用。而且,在这一点上,大多数每个React库和包都依赖相同的约定来在生产期间关闭开发人员时间助手。仅使用缩小的反应,所有这些潜在的优化也将留在桌面上。

最终,魔术归结为对process.env.NODE_ENV整个代码库的React嵌入引用这些就像功能切换一样。

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

上面是最常见的模式,其他库也遵循它。因此,要“禁用”这些检查,我们需要切换NODE_ENV"production"

禁用“开发模式”的正确方法是通过选择的捆绑程序。

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.

卡卡西理查德 2020.03.12

是的,它并没有得到很好的记录,但是在ReactJS 下载页面上,它讨论了开发和生产模式:

我们提供了两个版本的React:用于开发的未压缩版本和用于生产的精简版本。开发版本包括有关常见错误的额外警告,而生产版本包括额外的性能优化并去除所有错误消息。

基本上,React的最小版本是“开发”模式,React的最小版本是“生产”模式。

要处于“生产”模式,只需包含缩小版本 react-0.9.0.min.js

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android