webpack and react按需加载

45次阅读

共计 1846 个字符,预计需要花费 5 分钟才能阅读完成。

原理:CommonJS 与 import()
方法一:CommonJS 模块语法
利用 require.ensure,require.ensure() 是 webpack 特有的,已经被 import() 取代。
方法
require.ensure(
dependencies: String[],
callback: function(require),
errorCallback: function(error),
chunkName: String
)
方法二:import()
ES2015 loader 规范定义了 import() 方法,可以在运行时动态地加载 ES2015 模块
方法
import(‘Component’).then()
// or 在 async 中使用
await import(‘Component’)
demo
import React, {Component} from ‘react’;

class App extends Component {
handleClick = () => {
import(‘./moduleA’)
.then(({moduleA}) => {
// Use moduleA
})
.catch(err => {
// Handle failure
});
};

render() {
return (
<div>
<button onClick={this.handleClick}>Load</button>
</div>
);
}
}

export default App;
react-router 中使用按需加载
demo 地址,此处配合 create-react-app 使用,自己配置 webpack 合理需要配置 output.fileName 和 output.chunkFilename
方法一:使用 react.lazy
import {BrowserRouter as Router, Route, Switch} from ‘react-router-dom’;
import React, {Suspense, lazy} from ‘react’;

const Program1 = lazy(() => import(‘./Program1’));

const App = () => (
<Router>
<Suspense fallback={<div>Loading…</div>}>
<Switch>
<Route path=”/program1″ component={Program1}/>
</Switch>
</Suspense>
</Router>
);
查看代码
方法二:利用高阶组件
写一个高阶组件用于动态加载组件
// async Component
import React, {Component} from “react”;

export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);

this.state = {
component: null
};
}

async componentDidMount() {
const {default: component} = await importComponent();

this.setState({
component: component
});
}

render() {
const C = this.state.component;

return C ? <C {…this.props} /> : null;
}
}

return AsyncComponent;
}
查看代码
引用并使用该高阶组件做按需加载
import {BrowserRouter as Router, Route, Switch} from ‘react-router-dom’;
import asyncComponent from ‘./asyncComponent’;
import React, {Suspense} from ‘react’;

const Progran2 = asyncComponent(() => import(“./Program2″));

const App = () => (
<Router>
<Suspense fallback={<div>Loading…</div>}>
<Switch>
<Route exact path=”/program2” component={Program2}/>
</Switch>
</Suspense>
</Router>
);
查看代码
以上两种方法都是 react 官方推荐 code-splitting

正文完
 0