React 中的代码拆分
Code-Splitting 是 Webpack、Rollup 和 Browserify 等打包工具支持的一项功能,它可以创建多个可以在运行时动态加载的包。
随着网站变得越来越大并深入到组件中,它变得越来越重。当包含第三方库时尤其如此。代码拆分是一种有助于生成能够动态运行的包的方法。它还有助于提高代码效率,因为捆绑包包含所有必需的导入和文件。
捆绑及其效率:捆绑是将导入的文件与单个文件合并的方法。它是在Webpack、Rollup、Browserify的帮助下完成的,因为它们可以创建许多可以在运行时动态加载的包。
借助代码拆分,可以实现“延迟加载”,即只使用当前需要的代码。
- 默认导入方式如下:
javascript
import { add } from './math';
console.log(add(x, y));
// Here x, y are two numbers
javascript
import("./math").then(math => {
console.log(math.add(x, y));
});
// Here x, y are two numbers
javascript
import React, { Suspense } from 'react';
const Component = React.lazy(() => import('./Component'));
function MyComponent() {
return (
Loading... }>
javascript
import React, { Suspense } from 'react';
const ComponentOne =
React.lazy(() => import('./ComponentOne'));
const ComponentTwo =
React.lazy(() => import('./ComponentTwo'));
function MyComponent() {
return (
Loading... }>
javascript
import React, { Suspense } from 'react';
import ErrorBoundary from './ErrorBoundary';
const ComponentOne = React.lazy(() =>
import('./ComponentOne'));
const ComponentTwo = React.lazy(() =>
import('./ComponentTwo'));
const MyComponent = () => (
Loading... }>
javascript
import React from 'react';
import Suspense from 'react';
import lazy from 'react';
import {Route, Switch, BrowserRouter }
from 'react-router-dom';
const HomePage = lazy(() =>
import('./routes/HomePage'));
const AboutUs = lazy(() =>
import('./routes/AboutUs'));
const App = () =>
(Loading...