为什么我的 GlobalStyles 在使用样式化组件部署后不起作用?

Why are my GlobalStyles not working after deploying with styled components?

我在我的应用中使用 React、Redux、样式化组件和 GitHub 页面。

全局样式在开发中有效,但在部署到 GitHub 页面后未应用。

例如在 App.js

import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
   body {
      @import url("https://fonts.googleapis.com/css?family=Quicksand");
      color: red;
   }
`

const App = () => (
   <React.Fragment>
      <GlobalStyle />
      <Provider store={store}>
         <Router>
            <div>
              //REST OF APP
            </div>
         </Router>
      </Provider>
   </React.Fragment>
);

export default App;

问题在于当前在全局样式中使用@import时存在问题。如果您使用 Google 字体,解决方案是将 @import 取出并放在其他地方,例如 link 标签。

我也遇到过这种情况,您提供的有关该问题的信息对我有所帮助。谢谢@Brendan!

一旦您将其上传到 GitHub 页面,您对 https 的请求就会被阻止,因此您的 css 导入失败

有关在 createGlobalStyle 中使用 @import 的文档不清楚。与开发相比,生产似乎有所不同,很可能会停止 FOUC,如果您将 @import 移至顶层,那么它将正确导入并显示您的样式。

import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
   @import url("https://fonts.googleapis.com/css?family=Quicksand");
   body {
      color: red;
   }
`

const App = () => (
   <>
      <GlobalStyle />
      <Provider store={store}>
         <Router>
            <div>
              //REST OF APP
            </div>
         </Router>
      </Provider>
   </>
);

export default App;

我在部署使用 Google 字体的 React 应用程序的生产版本时遇到了同样的问题。然后我发现了这个很棒的项目:https://github.com/KyleAMathews/typefaces。它具有 所有 Google 字体,并通过 NPM 提供它们。

基本上,我所要做的就是

npm install typeface-pt-mono --save

然后在呈现我的 App.js 组件的顶级 index.js 中:

import "typeface-pt-mono";

就是这样。现在在我的应用程序中到处都有 css 指的是 font-family: "PT Mono" 很管用。