React项目的一些总结



使用 React 做了几个项目了,总结下。。。

本地开发

  • 跨域解决

    • webpack 的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 请求。

  • lodash优化

    • 使用lodash-webpack-pluginbabel-plugin-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优化

    • 忽略掉无用的国际化文件

      new webpack.ContextReplacementPlugin(
        // 需要被处理的文件目录位置
        /moment[\/\\]locale/,
        // 正则匹配需要被包括进来的文件
        /(en|zh-cn)\.js/
      )
      
    • 替代方案 day.js date-fns

  • 移除 console 和 debugger

    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        drop_console: true,
        drop_debugger: true
      },
      sourceMap: true
    })
    

上篇: Vue项目的一些总结 下篇: 相册项目的总结

站内搜索

分 类

标 签

相关链接