LoginSignup
7
4

More than 1 year has passed since last update.

next.js で コンポーネントだけのSCSSを使いたい時

Last updated at Posted at 2021-12-04

コンポーネントファイル Hoge.jsで、 CSS Modules を使用して、やりたいと思い。

まずsassをインストール

$ yarn add sass

SCSSファイル作成と読み込み

▼ styles/Hoge.scss

.hoge {
  background: red;
}

▼ components/Hoge.js

import test from "../styles/Hoge.scss";
const Hoge = () => {
  return (
    <div className={style.hoge}>
      <h1>こんにちは</h1>
    </div>
  );
};

export default Hoge;

下記の様なエラーが表示された。

Global CSS cannot be imported from files other than your Custom <App>. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to pages/_app.js. Or convert the import to Component-Level CSS (CSS Modules).
Read more: https://nextjs.org/docs/messages/css-global
Location: components/Hoge.js

グローバルでCSSを読み込みたいときは、_app.js でしか読み込めないよって言ってるっぽい。

【結論】コンポーネントで、CSS Modulesときは...

ファイル名が悪かった、
Hoge.scss にしてたのを Hoge.module.scss にする。

XXX.module.cssXXX.modile.scss の形にしないとグローバルCSSとして扱われて、 _app.js で読み込めないらしい。

結果下記の様になる

▼ styles/Hoge.module.scss

.hoge {
  background: red;
}

▼ components/Hoge.js

import test from "../styles/Hoge.module.scss";
const Hoge = () => {
  return (
    <div className={style.hoge}>
      <h1>こんにちは</h1>
    </div>
  );
};

export default Hoge;

おわり。

7
4
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
7
4