目前由H5集成开发的app小应用越来越来多,即在在一个原生的app平台下集成很多由web页面构成的小应用,因此我们可能在一个工程下开发多个小应用,部署整个工程之后,由原生端通过openWebview打开相关的路由,为了打开一个web应用时不附加别的应用的代码,不妨试试下面的js文件代码:
一、安装bundle-loader依赖
1
2 1npm install --save-dev bundle-loader
2
webpack相关配置如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 1module: {
2 rules: [
3 {
4 test: /\.(js|jsx)$/,
5 include: path.resolve(__dirname,"./src/modules/**/"),
6 use: [
7 {
8 loader: "bundle-loader",
9 options: {
10 lazy: true,
11 name: '[name]'
12 }
13 }
14 ]
15 }
16 ]
17}
18
二、定义一个高阶组件(HOC)
1
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 1import React, {Component} from 'react'
2
3class Bundle extends Component {
4 constructor(props) {
5 super(props);
6 this.state = {
7 mod: null
8}
9 }
10
11 componentWillMount() {
12 this.load(this.props)
13 }
14
15 componentWillReceiveProps(nextProps) {
16 if (nextProps.load !== this.props.load) {
17 this.load(nextProps)
18 }
19 }
20
21 load(props) {
22 this.setState({
23 mod: null
24});
25 props.load((mod) => {
26 this.setState({
27 mod: mod.default ? mod.default : mod
28 })
29 })
30 }
31
32 render() {
33 if (!this.state.mod)
34 return false;
35 return this.props.children(this.state.mod)
36 }
37}
38
39export default function lazy(lazyClass) {
40 return function Wrapper(props) {
41 return <Bundle load={lazyClass}>
42 {(Clazz) => <Clazz {...props} />}
43 </Bundle>
44 }
45}
46
三、路由相关配置
1
2
3
4 1import BindInfo from 'bundle-loader?lazy&name=userBind-chunk!../modules/userBind/info/Info';
2
3import Bundle from './Bundle';
4
1
2
3
4
5 1<Route path='userBind'>
2 <IndexRoute component={Bundle(UserBind)}/>
3 <Route path="info/:id" component={Bundle(BindInfo)}/>
4</Route>
5
四、正常进行webpack打包操作时可以看到代码已经拆分成了数个chunk.js,打开浏览器可以看到按需加载的效果。