Webpack 块样式和 react.lazy [英] Webpack chunk styles and react.lazy

查看:35
本文介绍了Webpack 块样式和 react.lazy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临与样式顺序相关的问题.就我而言,我有一个应用程序,我在其中使用 React.lazy,它将我们的应用程序(JS 和 CSS)拆分为小块(以提高初始加载性能).当我们访问第一个页面时出现问题(因此我们将获取与该页面相关的 JS + CSS),然后我们将转到另一个页面(并且还将 JS + CSS 获取到相关页面).在第二页上,我们覆盖了第一页上使用的一些样式.然后我们将返回到第一页(我们不会重新获取 CSS 和 JS 到相关页面,因为我们在缓存中)并且问题来了,导致覆盖样式使第一页崩溃.有什么办法可以解决吗?如果第二页的样式不会直接覆盖组件的 CSS 类,问题就不会出现:(

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 :(

推荐答案

使用 style-loader,你可以将一些 css 文件标记为惰性文件,并在挂载路由时调用 .use(),和 .unuse() 卸载路由时.

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 配置:

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',
        ],
      },
    ],
  },
};

来源:https://github.com/webpack-contrib/style-loader#lazystyletag

这篇关于Webpack 块样式和 react.lazy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆