更高的性能
有 scope hosting 功能,不再需要 rollup 来处理代码冗余
可与 react-router 结合,更优雅的做 dynamic import
最重要的一点是,我正经学 webpack 的时候 3 已结出了 - -
完整的 react spa 项目地址
GitHub 项目地址
这个一个完整的项目,这节相关的内容可在 router/routerMap.jsx 中找到.
第一步:安装 babel-plugin-syntax-dynamic-import
babel 用的是 babel-env,使用方法可以去 babel 官方学习,实践可看我项目的源代码.
npm i - D babel - plugin - syntax - dynamic - import
以后, 在. babelrc 文件的 plungins 中加上
第二步:安装 react-loadable
"syntax-dynamic-import"
.
npm i - S react - loadable
以后,我们就能愉快得做 dynamic import 了.
第三步: 编辑 routerMap
大功告成
import React from 'react';
import { HashRouter as Router, Route, Switch } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
import App from 'containers';
// 按路由拆分代码
import Loadable from 'react-loadable';
const MyLoadingComponent = ({ isLoading, error }) => {
// Handle the loading state
if (isLoading) {
return <div>Loading...</div>;
}
// Handle the error state
else if (error) {
return <div>Sorry, there was a problem loading the page.</div>;
}
else {
return null;
}
};
const AsyncHome = Loadable({
loader: () => import('../containers/Home'),
loading: MyLoadingComponent
});
const AsyncCity = Loadable({
loader: () => import('../containers/City'),
loading: MyLoadingComponent
});
const AsyncDetail = Loadable({
loader: () => import('../containers/Detail'),
loading: MyLoadingComponent
});
const AsyncSearch = Loadable({
loader: () => import('../containers/Search'),
loading: MyLoadingComponent
});
const AsyncUser = Loadable({
loader: () => import('../containers/User'),
loading: MyLoadingComponent
});
const AsyncNotFound = Loadable({
loader: () => import('../containers/404'),
loading: MyLoadingComponent
});
// 路由配置
class RouteMap extends React.Component {
render() {
return (
<Router history={history}>
<App>
<Switch>
<Route path="/" exact component={AsyncHome} />
<Route path="/city" component={AsyncCity} />
<Route path="/search/:category/:keywords?" component={AsyncSearch} />
<Route path="/detail/:id" component={AsyncDetail} />
<Route path="/user" component={AsyncUser} />
<Route path="/empty" component={null} key="empty" />
<Route component={AsyncNotFound} />
</Switch>
</App>
</Router>
);
// 说明
// empty Route
// https://github.com/ReactTraining/react-router/issues/1982 解决人:PFight
// 解决react-router v4改变查询参数并不会刷新或者说重载组件的问题
}
}
export default RouteMap;
我们可以运行 webpack,然后就能看到效果(图仅为 dev 环境,build 才会再打包一个 vendor.js,为什么要有 vendor.js,请见 devDependencies 和 dependencies 的区别 >> )
来源: https://juejin.im/post/5a582956518825734216d282