[英]Webpack v4 creating tiny chunks (by route)
這是我在 React 應用程序中使用的一些代碼。 我的路由是使用react-router-config編寫的,它允許我保持集中的方式,所以我總是知道去哪里修改或添加一些。
const routes = [
{
component: Root,
routes: [
{
path: "/",
exact: true,
component: Home
},
{
path: "/child/:id",
component: Child,
routes: [
{
path: "/child/:id/grand-child",
component: GrandChild
}
]
}
]
}
];
然后,假設 Child 組件是動態導入的:
const Child = lazy(() => import('./Child'));
我希望生成的塊包括 Child、它的導入/依賴項和 GrandChild 及其導入/依賴項; 但實際情況是,輸出是一個很小的 (1kb) 文件,其中僅包含此組件 (Child) 的行。
我怎樣才能讓 webpack 塊對/child/:id
路由很重要?
鑒於如此重要的功能缺乏解決方案(我已經到處搜索了 3 天),我最終還是手動完成了。
Webpack 允許指定動態導入將生成的塊的名稱。 如果您對功能中涉及的所有相關組件使用相同的名稱(如果功能是您的分塊方法),那么您可以執行以下操作:
/* ********************************** ACCOUNT ********************************** */
export const Account = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "cuenta" */ './pages/Account/Account'));
export const MyConsumption = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "cuenta" */ './pages/Account/MyConsumption/MyConsumption'));
export const MyAccount = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "cuenta" */ './pages/Account/MyAccount/MyAccount'));
export const Settings = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "cuenta" */ './pages/Account/Settings/Settings'));
export const Notifications = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "cuenta" */ './pages/Account/Notifications/Notifications'));
/* ********************************** OTHER PRODUCTS ********************************** */
export const Sectors = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "otros-productos" */ './pages/OtherProducts/Sectors/Sectors'));
export const SectorsList = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "otros-productos" */ './pages/OtherProducts/Sectors/SectorsList/SectorsList'));
export const SectorFile = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "otros-productos" */ './pages/OtherProducts/Sectors/SectorFile/SectorFile'));
export const SectorRiskReport = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "otros-productos" */ './pages/OtherProducts/Sectors/SectorRiskReport/SectorRiskReport'));
export const PressMail = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "otros-productos" */ './pages/OtherProducts/PressMail/PressMail'));
export const ValoraInfo = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "otros-productos" */ './pages/OtherProducts/Valora/ValoraInfo'));
export const ValoraReport = lazy(() => import(/* webpackPrefetch: true, webpackChunkName: "otros-productos" */ './pages/OtherProducts/Valora/ValoraReport'));
結果將是這樣的塊(注意黃色塊上方的 2 個塊,這是您在上面看到的代碼的結果):
這是值得分享的東西,也是一種創建有意義的塊的方法。 我的主要部分更輕,供應商也是如此,因此我們可以提供漸進式體驗並緩存用戶將一次又一次使用的資源。
我希望我能幫助那里的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.