代码拆分
代码拆分允许你将代码拆分成小块,然后可以按需加载,而不是在用户可以使用之前下载整个应用。
¥Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand.
此项目设置支持通过 动态 import()
进行代码拆分。它的 提案 处于第 4 阶段。import()
类函数形式将模块名称作为参数并返回一个 Promise
,它始终解析为模块的名称空间对象。
¥This project setup supports code splitting via dynamic import()
. Its proposal is in stage 4. The import()
function-like form takes the module name as an argument and returns a Promise
which always resolves to the namespace object of the module.
这是一个例子:
¥Here is an example:
moduleA.js
const moduleA = 'Hello';
export { moduleA };
App.js
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;
这将使 moduleA.js
及其所有唯一依赖成为一个单独的块,仅在用户单击 '加载' 按钮后加载。有关创建的块的更多信息,请参阅 生产构建 部分。
¥This will make moduleA.js
and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. For more information on the chunks that are created, see the production build section.
如果你愿意,也可以将其与 async
/ await
语法一起使用。
¥You can also use it with async
/ await
syntax if you prefer it.
使用 React Router
¥With React Router
如果你使用的是 React Router,请查看 本教程
¥If you are using React Router check out this tutorial
另请查看 React 文档中的 代码拆分 部分。
¥Also check out the Code Splitting section in React documentation.