LoginSignup
0
0

More than 3 years have passed since last update.

【React】styled-componentsのGlobalStyleがデプロイすると効かなくなるときの対処法

Last updated at Posted at 2019-08-15

問題

Styled Components v4で実装されたAPI、createGlobalStyleでグローバルスタイルを適用します。

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 0;
    @import url(http://fonts.googleapis.com/earlyaccess/notosansjp.css);
    font-family: 'Noto Sans JP', sans-serif;
  }
`;

すると、ローカル環境では正常に機能するが、デプロイするとグローバルスタイルが適用されないというケースがあります。

原因

ざっと調べた限りでは、これという原因はわかりませんでした。
たびたびissueでも取り上げられているようです。

ただ、@importの挙動が不安定ということらしいので、上記のコードの例に限っては、body内で@importしているところが怪しそうです。

対処法

@importをトップレベルに移動してきます。

const GlobalStyle = createGlobalStyle`
  @import url(http://fonts.googleapis.com/earlyaccess/notosansjp.css);
  * {
    margin: 0;
    padding: 0;
    font-family: 'Noto Sans JP', sans-serif;
  }
`;

これで私の環境では問題は解消されました。
ただ、できれば@importは使わないほうがいいかもしれません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0