Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

组件编写规范之:proptypes #18

Open
youngwind opened this issue Jan 1, 2016 · 0 comments
Open

组件编写规范之:proptypes #18

youngwind opened this issue Jan 1, 2016 · 0 comments
Labels

Comments

@youngwind
Copy link
Owner

前言

随着组件写得越来越大,越来越复杂,组件对自身的自定就显得越来越重要,要是一个组件没有任何关于自身的说明,别人怎么调用你的呢?

组件必须写proptypes

参考react的官方说明文档:
http://facebook.github.io/react/docs/reusable-components.html#prop-validation
组件可以通过proptypes校验传进来的数据类型,当向 props 传入无效数据时,JavaScript 控制台会抛出警告。除了数据校验以外,proptypes也是一个很好的说明组件调用api的地方。
注意为了性能考虑,只在开发环境验证 propTypes。虽然文档中列举了各个规则,但是在这里却没有明确指出如何实现只在开发环境严重propTypes这一个功能。后来我找到了集成在webpack当中方法。

如何做到“只在开发环境验证propTypes"?

react官方说明文档:
https://facebook.github.io/react/downloads.html
里面写到:

We provide two versions of React: an uncompressed version for development and a minified version for production. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.
If you're just starting out, make sure to use the development version.

Note: by default, React will be in development mode. To use React in production mode, set the environment variable NODE_ENV to production (using envify or webpack's DefinePlugin). A minifier that performs dead-code elimination such as UglifyJS is recommended to completely remove the extra code present in development mode.

显然,react本身是有两个版本的:开发版本和线上版本。开发版本会进行错误检测,包括proptypes的检测,但是线上版本不会。其中的区别在于环境变量。后一段话指出,可以通过envify或者webpack定义环境变量达到目的。因为我用的是webpack,所以我找到了webpack对应的解决方案。

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

具体参考例子:webpack/webpack#292 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant