问题
I am facing the issue related to the order of the styles. In my case, I have an app, where I am using React.lazy, which will split our app ( JS and CSS ) to small chunks ( to improve initial load performance ). Problem is coming when we visit the first page ( so we will fetch JS + CSS related to that page ), then we will go to another page ( and also fetch JS + CSS to related page ). On the second page, we were overriding some styles, which we were using on the first page. Then we will back to the first page ( we will not re-fetch CSS and JS to the related page, cause we have it in cache ) and the problem is coming, cause that override styles crash the first page. Is there any way to fix it? The problem will be not coming if the styles from the second page will not override the CSS class of the components directly :(
回答1:
With style-loader, you could mark some of your css files lazy, and call .use()
when mounting the route, and .unuse()
when unmounting the route.
import styles from './styles.lazy.css';
export function LegacyRoute() {
useLayoutEffect(() => {
styles.use();
return () => { styles.unuse() };
}, []);
return <p>Hello World</p>;
}
webpack config:
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
exclude: /\.lazy\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.lazy\.css$/i,
use: [
{ loader: 'style-loader', options: { injectType: 'lazyStyleTag' } },
'css-loader',
],
},
],
},
};
Source: https://github.com/webpack-contrib/style-loader#lazystyletag
来源:https://stackoverflow.com/questions/60632062/webpack-chunk-styles-and-react-lazy