React应用变得复杂,打包之后的bundle会变得过大,这时可以考虑code split:

// in package.json
devDependencies: {
...,
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"react-loadable": "^5.3.1",
...
}

// in .babelrc
{
  ...,
  "plugins": ["syntax-dynamic-import"],
  ...
}

// in webpack.config.js
...
output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'js/[name].bundle.js',
    chunkFilename: 'chunks/[name].[chunkhash:8].chunk.js'
  },
...

实际的使用:

// in app root

// 这里在app入口文件设置webpack运行时的根路径为输出的chunks文件的根目录,
// 如果忽略或在webpack.config.js中指定publicPath,会导致import()
// 时请求的地址出错
__webpack_public_path__ = app.appBasePath + '/public/'

// 引入异步的高阶load组件。地址:https://github.com/thejameskyle/react-loadable
// 或者自己写asyncComponent,比较简单
// 比如:https://gist.github.com/lencioni/643a78712337d255f5c031bfc81ca4cf
import Loadable from 'react-loadable'

// 加载页面js时的loading组件
import Loading from './components/Loading'

// 异步加载一个实际的组件
const AsyncHomePerson= Loadable({
  loader: () => import ('./containers/home/HomePerson'),
  loading: Loading
})

// router 里照常使用
...
<Route path={routes.catalogue} component={AsyncHomeCatalogue} />
...

最后实际打包的输出如下:

实际会在路由到某个页面才去加载对应的chunk文件

参考

https://webpack.js.org/guides/code-splitting/

https://webpack.js.org/concepts/output/#advanced

https://reacttraining.com/react-router/web/guides/code-splitting

https://serverless-stack.com/chapters/code-splitting-in-create-react-app.html