新建 Bundle 组件
bundle.js
import React, { Component } from "react";
class Bundle extends Component { state = { mod: null, };
componentWillMount() { this.load(this.props); }
componentWillReceiveProps(nextProps) { if (nextProps.load !== this.props.load) { this.load(nextProps); } }
load(props) { this.setState({ mod: null, }); props.load((mod) => { this.setState({ mod: mod.default ? mod.default : mod, }); }); }
render() { return this.state.mod ? this.props.children(this.state.mod) : null; } }
export default Bundle;
|
使用 bundle-loader
routes.js
import React from "react"; import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Bundle from "./bundle";
import Index from "./Index"; import Page1 from "bundle-loader?lazy&name=page1!./Page1"; import Page2 from "bundle-loader?lazy&name=page2!./Page2";
const loadComponent = (component) => () => <Bundle load={component}>{(Component) => <Component />}</Bundle>;
const routes = () => ( <Router> <div> <Route exact path="/" component={Index} /> <Route path="/page1" component={loadComponent(Page1)} /> <Route path="/page2" component={loadComponent(Page2)} /> </div> </Router> );
export default routes;
|
这样就实现了按需加载
wepack 里配置 hash 值
output: { filename: 'static/js/[name].[chunkhash:8].js', chunkFilename: 'static/js/[name].[chunkhash:8].js', path: resolve(__dirname, 'server/dist'), publicPath: '/' }
|