使用 React 做了几个项目了,总结下。。。
跨域解决
dev-server使用了非常强大的 http-proxy-middleware 包。创建src/setupProxy.js,写入代理配置,参见文档。react 热更新
使用react-hot-loader。
webpack.config.js
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
plugins: ['react-hot-loader/babel'],
},
}
yarn add react-dom@npm:@hot-loader/react-dom
减少渲染的节点/降低渲染计算量(复杂度)
不要在render函数进行不必要的计算。
使用React.Fragments替代空 div。
不变的事件处理器
data-*属性(值只能是字符串),通过event.target.dataset.*去获取。inline 一些小文件,减少 http 请求。
使用script-ext-html-webpack-plugin将js引入的文件进行inline。
使用inline-source-webpack-plugin将html引入的js文件进行inline。
lodash优化
坑 优化后的一些方法的的第二参数不能用字符串,要用回调。例子:
_.sumBy(objects, function(o) {
return o.n
}) // ok
_.sumBy(objects, 'n') // error
_.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], function(o) {
return o.x
}) // ok
_.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x') // error
moment优化
移除 console 和 debugger
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
drop_console: true,
drop_debugger: true
},
sourceMap: true
})