首页 > 解决方案 > 从也可以导入的样式组件中创建全局样式的替代方法

问题描述

我们目前正在加载字体和其他一些像这样的全局样式:

import { createGlobalStyle } from 'styled-components';

export default createGlobalStyle`
  @font-face {
     font-family: 'Name';
     font-style: normal;
     font-weight: 400;
     font-display: swap;
     src: url(https://fonts.gstatic.com/s/name/v12/iJWZBXyIfDnIV5PNhY1KTN7Z-Yh-B4iFU0U1Z4Y.woff2) format('woff2');
  }

  // more fonts..
}

在每个_app.tsx(来自回购中的每个项目)中,我们只是

import GlobalStyle from @our-company/ui;
// few other imports

const AppProviders = ({ children, messages, locale }: Props): JSX.Element => {
  return (
    <IntlProvider
      locale={locale || 'en-GB'}
      key={locale}
      messages={messages[locale]}
      defaultLocale="en-GB"
    >
      <GlobalStyle />
      <DsThemeProvider
        locale={locale}
      >
        {children}
      </DsThemeProvider>
    </IntlProvider>
  );
};

但是我们注意到GlobalStyle在单击复选框元素时会导致不必要的字体重新加载(尝试将其放在 .css 中并加载它,然后再也不会发生)。

知道如何在GlobalStyle不使用样式组件的情况下将这些样式导出为名称,这样我们就不必更改import项目中所有应用程序的所有内容?

标签: reactjsstyled-components

解决方案


为什么您不创建 main.css 并将其导入您的 index.css 或 app.css ,它的下载和缓存在用户浏览器上,因此您不再需要使用全局样式的组件


推荐阅读