本文Demo的完整工程代码, 参考dva-lazy-loading
开始
dva new dva-lazy-loading
首页
cnpm i --save antd
cnpm i --save-dev babel-plugin-import
vim .roadhogrc
{
"entry": "src/index.js",
"env": {
"development": {
"extraBabelPlugins": [
"dva-hmr",
"transform-runtime",
["import", { "libraryName": "antd", "style": "css" }]
]
},
"production": {
"extraBabelPlugins": [
"transform-runtime",
["import", { "libraryName": "antd", "style": "css" }]
]
}
}
}
vim src/routes/IndexPage.js
import React from 'react';
import { connect } from 'dva';
import { Button } from 'antd';
import styles from './IndexPage.css';
function IndexPage() {
return (
<div className={styles.normal}>
<Button>Antd Button</Button>
<h1 className={styles.title}>Yay! Welcome to dva!</h1>
<div className={styles.welcome} />
<ul className={styles.list}>
<li>To get started, edit <code>src/index.js</code> and save to reload.</li>
<li><a href="https://github.com/dvajs/dva-docs/blob/master/v1/en-us/getting-started.md">Getting Started</a></li>
</ul>
</div>
);
}
IndexPage.propTypes = {
};
export default connect()(IndexPage);
npm run build
File sizes after gzip:
90.51 KB dist/index.js
10.11 KB dist/index.css
npm start
此时打开浏览器访问地址http://localhost:8000/#/ 获取包大小如下
第二页(非懒加载)
cnpm i --save lodash
vim src/routes/SecondPage.js
import React from 'react';
import { connect } from 'dva';
import _ from 'lodash';
function SecondPage() {
return (
<div>
{_.indexOf(['hello', 'world'], 'hello')}
</div>
);
}
SecondPage.propTypes = {
};
export default connect()(SecondPage);
vim src/router.js
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import IndexPage from './routes/IndexPage';
import SecondPage from './routes/SecondPage';
function RouterConfig({ history }) {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={IndexPage} />
<Route path="/second" exact component={SecondPage} />
</Switch>
</Router>
);
}
export default RouterConfig;
npm run build
File sizes after gzip:
114.49 KB dist/index.js
10.11 KB dist/index.css
npm start
此时打开浏览器访问地址http://localhost:8000/#/或http://localhost:8000/#/second 获取包大小如下
第二页(懒加载)
vim src/router.js
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import dynamic from 'dva/dynamic';
import IndexPage from './routes/IndexPage';
function RouterConfig({ history, app }) {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={IndexPage} />
<Route
path="/second"
exact
component={
dynamic({
app,
component: () => import('./routes/SecondPage'),
})
}
/>
</Switch>
</Router>
);
}
export default RouterConfig;
npm run build
File sizes after gzip:
92.5 KB dist/index.js
24.48 KB dist/0.async.js
10.11 KB dist/index.css
npm start
此时打开浏览器访问地址http://localhost:8000/#/ 获取包大小如下
此时打开浏览器访问地址http://localhost:8000/#/second 获取包大小如下
参考
更多文章, 请支持我的个人博客