Router4
bundle-loader
Router4移除了getComponent,改用bundle-loader实现,其核心实现仍然是require.ensure1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81// 方式一
// 1.创建加载器
class LazyLoader extends React.Component {
constructor(props) {
super(props);
this.state = {
component: null
}
}
componentWillMount() {
this._load();
}
componentWillReceiveProps(nextProps) {
if (this.props.component != next.component) {
return;
}
this._load();
}
_load(){
this.props.component(comp => {
this.setState({
component: comp.default ? comp.default : comp
});
});
}
render() {
const LazyComponent = this.state.component;
return LazyComponent ? this.props.children(LazyComponent) : null;
}
}
// 2.引用异步组件
import List from 'bundle-loader?lazy&name=lazy.[name]!./component/list.js';
//List(function(file){ // do something});
// 3.使用
const AsyncComponent = (props) => (
<LazyLoader component={List}>
{
(Comp) => <Comp {...props} />
}
</LazyLoader>
)
class App extends React.Component {
render() {
return (
<Router>
<Route path="list" component={AsyncComponent}></Route>
</Router>
);
}
}
// 方式二: HOC
import List from 'bundle-loader?lazy&name=lazy.[name]!./component/list.js';
function HOC(getComponent){
return class ProxyComp extends React.Component {
constructor(props) {
super(props);
this.state = {
component: null
}
}
componentWillMount() {
this._load();
}
_load(){
getComponent(comp => {
this.setState({
component: comp
});
});
}
render() {
const LazyComponent = this.state.component;
return LazyComponent ? <LazyComponent {...this.props} /> : null;
}
}
}
const AsyncComponent = HOC(List);
import()
1 | function HOC(getComponent){ |
Router3
require.ensure
1 | const $FILE_PATH = './component/list.js'; |
import()
1 | function lazyLoader(_, cb) { |