[英]Code splitting loads all chunk files on chrome but load them separately in firefox
I created my app with create-react-app
.我使用create-react-app
创建了我的应用程序。
In my website , I used lazy loading for page components:在我的网站中,我对页面组件使用了延迟加载:
import HomePage from '~/containers/pages/HomePage/Loadable';
import RestaurantPage from '~/containers/pages/RestaurantPage/Loadable';
// other routes
const RoutesList = ({ history }) => {
history.listen(() => {
window.scrollTo(0, 0);
});
return (
<DefaultLayout history={history}>
<Switch>
<Route path="/restaurant/:slug" component={RestaurantPage} />
// other routes
<Route exact path="/" component={HomePage} />
<Route component={ErrorPage} statusCode="404" />
</Switch>
</DefaultLayout>
);
};
And my Loadable component looks like this:我的可加载组件如下所示:
import React from 'react';
import LoadingIndicator from '~/components/common/LoadingIndicator';
import loadable from '~/utils/loadable';
export default loadable(() => import('./index'), {
fallback: <LoadingIndicator />,
});
With this for lazy component:有了这个惰性组件:
/* eslint-disable react/jsx-props-no-spreading */
import React, { lazy, Suspense } from 'react';
const loadable = (importFunc, { fallback = null } = { fallback: null }) => {
const LazyComponent = lazy(importFunc);
return (props) => (
<Suspense fallback={fallback}>
<LazyComponent {...props} />
</Suspense>
);
};
export default loadable;
So my problem is, the code splitting works fine in firefox.所以我的问题是,代码拆分在 firefox 中工作正常。 When clicking a link in a the menu, the separated chunk files are loading only when accessing the new page.单击菜单中的链接时,仅在访问新页面时才加载分隔的块文件。
But in chrome, every chunk files are loaded.但是在 chrome 中,每个块文件都会被加载。
So I found the solution.所以我找到了解决方案。 But it was tricky and linked to my configuration.但这很棘手,并且与我的配置有关。
So what happened is that I'm using a custom webpack config (with craco), and I addded a plugin, PreloadWebpackPlugin
to add preload to fonts, images.所以发生的事情是我正在使用自定义 webpack 配置(带有 craco),并且我添加了一个插件PreloadWebpackPlugin
来将预加载添加到 fonts,图像。
By default, this plugin also add "preload" to chunks.默认情况下,此插件还会向块添加“预加载”。 But webpack is smart, it doesn't add the not needed chunk files in the first load.但是 webpack 很聪明,它不会在第一次加载时添加不需要的块文件。
But what was happening is that I had the hot module reload file was listing all chunk files (so it can restart when there is a change), and this config was "preloading" them all.但是发生的事情是我让热模块重新加载文件列出了所有块文件(因此它可以在发生更改时重新启动),并且这个配置正在“预加载”它们。
So the only thing I had to do is:所以我唯一要做的就是:
webpackConfig.plugins.push(
new PreloadWebpackPlugin({
rel: 'preload',
include: 'allAssets',
fileWhitelist: [/main.chunk.js/, /\.webp/, /\.woff2/, /\.woff/],
}),
);
Only add preload to main chunk file.仅将预加载添加到主块文件。
Now it works.现在它起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.