我正在使用 React.lazy 进行基于路由的代码拆分。在某些页面中,有到其他页面的链接。在这种情况下,它也会为该链接页面创建块。
网络包
optimization: {
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
vendor: {
test: new RegExp(
/[\\/]node_modules[\\/]/,
),
chunks: 'all',
name: 'vendor',
enforce: true,
},
},
},
},
Routes.js
const Home = React.lazy(() => import('./Pages/Home' /* webpackChunkName: "home" */));
const Profile = React.lazy(() => import('./Pages/Profile' /* webpackChunkName: "profile" */))
const Settings = React.lazy(() => import('./Pages/Settings' /* webpackChunkName: "Settings" */))
const Routes = () => {
return (
<Suspense fallback={<div>loading...</div>}>
<Switch>
<Route path="/" exact component={Home}/>
<Route path="/Profile" component={Profile}/>
<Route path="/Settings" component={Settings}/>
</Switch>
</Suspense>
)
}
首页
export default function Home() {
return (
<div>
<p>Home</p>
<Link to="/profile">Go to Profile</Link>
<Link to="/settings">Go to Settings</Link>
</div>
)
}
这里我得到了下面的块 -
app.[hash].js
runtime.[hash].js
vendor.[hash].js
Home.[hash].js
Profile.[hash].js
Home~Profile.[hash].js
Home~Setting.[hash].js
得到最后两个块的原因是什么?
答案 0 :(得分:0)
你也可以通过一些 webpack 包分析器检查这个块的内容,看看里面有什么。两个页面之间很可能存在一些类似的供应商包,因此从性能角度来看,最好将这些包放在共享块中,而不是在每个块中复制这些包。