简体   繁体   English

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

[英]How to turn on/off ReactJS 'development mode'?

Started using ReactJS's prop validation feature , which as the docs say only works in 'development mode' for performance reasons.开始使用 ReactJS 的prop 验证功能,正如文档所说,出于性能原因,该功能仅适用于“开发模式”。

React seems to be validating the properties of a particular component I've annotated, but I don't remember explicitly turning on 'development mode'. React 似乎正在验证我注释的特定组件的属性,但我不记得明确打开“开发模式”。

I tried searching for how to trigger/toggle development mode, but haven't had any luck.我尝试寻找如何触发/切换开发模式,但没有任何运气。

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. 另一个答案假设您正在使用来自react的外部预构建文件,而正确的是大多数人不会或应该将 React作为包使用。 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; 归根结底,React在整个代码库中嵌入了对process.env.NODE_ENV引用; these act like a feature toggle. 这些就像一个功能切换。

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

The above is the the most common pattern, and other libraries follow it as well. 以上是最常见的模式,其他库也遵循它。 So to "disable" these checks we need to toggle NODE_ENV to "production" 因此要“禁用”这些检查,我们需要将NODE_ENV切换为"production"

The proper way to disable "dev mode" is through your bundler of choice. 禁用“开发模式”的正确方法是通过您选择的捆绑器。

webpack 的WebPack

Use the DefinePlugin in your webpack config like so: 在webpack配置中使用DefinePlugin ,如下所示:

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

Browserify Browserify

Use the Envify transform and run your browserify build step with NODE_ENV=production ( "set NODE_ENV=production" on Windows) 使用Envify转换并使用NODE_ENV=production运行browserify构建步骤(在Windows上"set NODE_ENV=production"

Result 结果

This will produce output bundles that has all instances of process.env.NODE_ENV replaced with the string literal: "production" 这将生成输出包,其中所有process.env.NODE_ENV实例都替换为字符串文字: "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. DCE是指minifier足够聪明,意识到: "production" !== "production" 总是假的,所以只删除if块中的任何代码,节省你的字节。

Yeah, it's not really well documented, but on the ReactJS download page it talks about development and production modes: 是的,它没有很好的文档,但在ReactJS 下载页面上它讨论了开发和生产模式:

We provide two versions of React: an uncompressed version for development and a minified version for production. 我们提供了两个版本的React:一个用于开发的未压缩版本和一个用于生产的缩小版本。 The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages. 开发版本包含有关常见错误的额外警告,而生产版本包括额外的性能优化并删除所有错误消息。

Basically, the unminified version of React is "development" mode, and the minified version of React is "production" mode. 基本上,React的未公开版本是“开发”模式,而React的缩小版本是“生产”模式。

To be in "production" mode, just include the minified version react-0.9.0.min.js 要处于“生产”模式,只需包含缩小版本react-0.9.0.min.js

I posted this elsewhere but, frankly, here would be a better place. 我在其他地方贴了这个,但坦率地说,这里会是一个更好的地方。

Assuming you install React 15.0.1 with npm, import react from 'react' or react = require('react') will run ./mode_modules/react/lib/React.js which is React's raw source. 假设您使用npm安装React 15.0.1, import react from 'react'或者react = require('react')将运行./mode_modules/react/lib/React.js这是React的原始源。

The React docs suggest you use ./mode_modules/react/dist/react.js for development and react.min.js for production. React文档建议您使用./mode_modules/react/dist/react.js进行开发,使用react.min.js进行生产。

Should you minify /lib/React.js or /dist/react.js for production, React will display a warning message that you've minified non-production code: 如果你将/lib/React.js/dist/react.js缩小为生产,React会显示一条警告消息,说明你已经缩小了非生产代码:

Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See fb.me/react-minification for more details.

react-dom, redux, react-redux behave similarly. react-dom,redux,react-redux表现相似。 Redux displays a warning message. Redux显示警告消息。 I believe react-dom does too. 我相信react-dom也是如此。

So you are clearly encouraged to use the production version from /dist . 因此,显然鼓励您使用/dist的生产版本。

However if you minify the /dist versions, webpack's UglifyJsPlugin will complain. 但是如果你缩小/dist版本,webpack的UglifyJsPlugin会抱怨。

WARNING in ../~/react/dist/react.js Critical dependencies: 4:478-485 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results. @ ../~/react/dist/react.js 4:478-4851

You cannot avoid this message because UglifyJsPlugin can only exclude webpack chunks, not individual files. 您无法避免此消息,因为UglifyJsPlugin只能排除webpack块,而不能排除单个文件。

I use the both the development and production /dist versions myself. 我自己使用开发和生产/dist版本。

  • Webpack has less work to do and finishes a bit sooner. Webpack的工作量较少,并且可以更快地完成。 (YRMV) (YRMV)
  • React docs say /dist/react.min.js is optimised for production. React docs说/dist/react.min.js针对生产进行了优化。 I've read no proof that 'process.env': { NODE_ENV: JSON.stringify(IS_PRODUCTION ? 'production' : 'development') } plus uglify does as good a job as '/dist/react.min.js`. 我没有读过'process.env': { NODE_ENV: JSON.stringify(IS_PRODUCTION ? 'production' : 'development') }加上uglify与'/ dist / react.min.js'一样好的证据。 I've read no proof you get the same resulting code. 我没有看到你得到相同结果代码的证据。
  • I get 1 warning message from uglify rather than 3 from the react/redux ecosystem. 我收到来自uglify的1条警告信息,而不是来自react / redux生态系统的3条警告信息。

You can have webpack use the /dist versions with: 您可以让webpack使用/dist版本:

resolve: {
    alias: {
      'react$': path.join(__dirname, 'node_modules', 'react','dist',
        (IS_PRODUCTION ? 'react.min.js' : 'react.js')),
      'react-dom$': path.join(__dirname, 'node_modules', 'react-dom','dist',
        (IS_PRODUCTION ? 'react-dom.min.js' : 'react-dom.js')),
      'redux$': path.join(__dirname, 'node_modules', 'redux','dist',
        (IS_PRODUCTION ? 'redux.min.js' : 'redux.js')),
      'react-redux$': path.join(__dirname, 'node_modules', 'react-redux','dist',
        (IS_PRODUCTION ? 'react-redux.min.js' : 'react-redux.js'))
    }
  }

For webpack based build, I used to setup separate webpack.config.js for DEV and PROD. 对于基于webpack的构建,我曾经为DEV和PROD设置了单独的webpack.config.js。 For Prod, resolve the alias as below 对于Prod,请解决别名,如下所示

     alias: {
        'react$': path.join(__dirname, 'node_modules', 'react','dist','react.min.js'),
        'react-dom$': path.join(__dirname, 'node_modules', 'react-dom','dist','react-dom.min.js')
    }

You can find the working one from here 你可以从这里找到工作的

If you're working from something like this ReactJS.NET / Webpack tutorial , you can't use process.env to switch React development mode on/off as far as I can tell. 如果你正在使用这个ReactJS.NET / Webpack教程 ,你就不能使用process.env来打开/关闭React开发模式。 This sample links to react.js directly (see Index.cshtml ), so you just have to pick .min.js or the non-minified variant by changing the URL. 此示例直接链接到react.js(请参阅Index.cshtml ),因此您只需通过更改URL来选择.min.js或非缩小版本。

I'm not sure why that is the case, because the sample's webpack.config.js has a comment that seems to imply the externals: { react: 'React' } would do the job, but then goes ahead and includes react directly into the page. 我不确定为什么会这样,因为样本的webpack.config.js有一个注释似乎意味着externals: { react: 'React' }将完成这项工作,但随后继续并包括直接反应这页纸。

For only Webpack v4 users: 仅适用于 Webpack v4用户:

Specifying mode: production and mode: development in your Webpack config will define process.env.NODE_ENV using the DefinePlugin by default. 指定mode: productionmode: development Webpack配置中的mode: development将默认使用DefinePlugin定义process.env.NODE_ENV No additional code necessary! 无需额外的代码!

webpack.prod.js (taken from docs) webpack.prod.js(摘自docs)

const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  mode: 'production',
});

And in our JS: 在我们的JS中:

console.log(process.env.NODE_ENV) // --> 'development' or 'production'

Webpack Docs: https://webpack.js.org/guides/production/#specify-the-mode Webpack文档: https ://webpack.js.org/guides/production/#specify-the-mode

I use a manual build process that runs through Webpack, so it was a two-step process for me:我使用通过 Webpack 运行的手动构建过程,所以对我来说这是一个两步过程:

  1. Set the environment variable from package.json using the cross-env package:使用 cross-env 包从 package.json 设置环境变量:

    "scripts": { "build-dev": "cross-env NODE_ENV=development webpack --config webpack.config.js", "build-prod": "cross-env NODE_ENV=production webpack --config webpack.config.js" }

  2. Change the webpack.config.js file to use the environment variable (which is passed-on to React to determine if we are in development or production mode), and disable minimizing the produced bundle if we are in development mode so we can see the actual names of our components.更改 webpack.config.js 文件以使用环境变量(传递给 React 以确定我们是处于开发模式还是生产模式),并在处于开发模式时禁用最小化生成的包,以便我们可以看到我们组件的实际名称。 We need to use webpack's optimization property in our webpack.config.js file for this:为此,我们需要在webpack.config.js文件中使用 webpack 的优化属性:

    optimization: { nodeEnv: process.env.NODE_ENV, minimize: process.env.NODE_ENV === 'production' }

webpack v4.41.5, React v16.9.19, cross-env v7.0.0, node v10.16.14 webpack v4.41.5、React v16.9.19、跨环境 v7.0.0、节点 v10.16.14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM