我一直在尝试使用React的惰性代码拆分功能,如此处所述:https://reactjs.org/docs/code-splitting.html,但是我看到了一些意外的行为,需要我的帮助来理解和纠正。
这是我的路由文件,触发代码拆分:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';
const APage = lazy(() => import(/* webpackChunkName: "APage" */ '../pages/APage'));
const BPage = lazy(() => import(/* webpackChunkName: "BPage" */ '../pages/BPage'));
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/a" component={APage}/>
<Route exact path="/b" component={BPage}/>
</Switch>
</Suspense>
</Router>
);
为生产而构建时,它会生成4个文件:
app.js // the main bundle, includes react, react-dom, etc.
APage.js // contains only code needed to render APage
BPage.js // contains only code needed to render BPage
APage~BPage.js // contains components shared by APage and BPage
这可以按预期工作,并且能够呈现两条路线。
但是,当我将导入添加到APage
组件时,就像这样:
import React, { Component } from 'react';
import { usefulFunction } from '../lib/utils';
export default class LpAPage extends Component {
componentDidMount() {
usefulFunction();
}
render() {
return (
<h1>Landing Page A</h1>
)
}
}
usefulFunction
的代码最终出现在主捆绑包(app.js
)中,无论使用哪种路由,它都包含在初始负载中。
如何更改此代码,以便仅在需要时才将usefulFunction
包含在APage.js
块中?