【问题标题】:is there any way to disable or speed up React PropType validation in development mode?有没有办法在开发模式下禁用或加速 React PropType 验证?
【发布时间】:2016-04-22 04:30:43
【问题描述】:

据我所知,禁用 React PropType 验证的唯一方法是将 process.env.NODE_ENV 定义为 'production' 来丑化 React。

但是,我想使用没有运行时 PropType 验证的开发模式,原因如下:

  • 它们显着降低了我的应用程序的速度。 PropType 验证是分析结果中的首要问题,因为:
    • 我有一个相当深的组件层次结构,在多个级别进行 PropType 验证(是的,我确实有适当的 shouldComponentUpdate 等)
    • 我使用的是 Redux,这意味着所有更新都从层次结构的顶部或附近开始
    • 我有鼠标拖动交互,争取每秒更新 30 次
  • 我仍然希望看到所有其他 React 警告和错误,它们也会在生产模式下被禁用。
  • Flowtype 显然可以在很多情况下静态验证 PropTypes。

如果没有别的,我可以为babel-plugin-react-transform 创建一个转换器,去除所有组件'propTypes(或者可能只是那些我以某种方式注释的组件),但我想知道是否有更简单的方法来做到这一点,因为 React 可以很容易地提供一个编译时标志来禁用 PropType 验证。

更新:那个 babel 插件已经存在 (https://www.npmjs.com/package/babel-plugin-react-remove-prop-types)

【问题讨论】:

    标签: performance validation reactjs react-proptypes


    【解决方案1】:

    简答:没有简单的标志可以仅禁用 PropType 验证


    目前,PropType 验证由__DEV__ 全局变量启用。 如果将其更改为 false,您将丢失其他 React 警告和错误,正如您所说,您不能。

    此代码 here in ReactDOMFactories 显示如何选择 ReactElementValidatorReactElement 工厂来定义元素创建的工作方式:

    function createDOMFactory(tag) {
      if (__DEV__) {
        return ReactElementValidator.createFactory(tag);
      }
      return ReactElement.createFactory(tag);
    }
    

    ReactElementValidator.createElement 中你可以看到它调用ReactElement.createElement 然后validatePropTypes

    var ReactElementValidator = {
    
      createElement: function(type, props, children) {
    
        /* some code here */
    
        var element = ReactElement.createElement.apply(this, arguments);
    
        /* some code here */
    
        // here would be a good place for the flag that you need
        validatePropTypes(element);
    
        return element;
      }
    

    我不确定这些信息如何帮助您,但至少表明没有像您想的那样通过标志禁用 PropType 的简单方法。


    更新 - 2017 年 5 月 10 日
    Andy 发现有一个 Babel Plugin that removes Prop Types
    我没有测试它。请务必阅读插件的Is it safe? 部分,看看它是否适合您。

    【讨论】:

    • 这很酷,我从来没有读过 React 内部的很多内容,但是他们使元素创建像这样可插入是很整洁的。
    • 我添加了一个关于我发现删除 proptypes (npmjs.com/package/babel-plugin-react-remove-prop-types) 的 babel 插件的注释
    • 我现在不清楚 - 它们是自动从 production 构建中删除的,还是需要 Babel 插件?
    猜你喜欢
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-30
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多