LoginSignup
8
3

More than 3 years have passed since last update.

Next.js 9.3 ビルトインsass autoprefixer メモ

Last updated at Posted at 2020-03-28

ビルトインSassサポート

Next.js 9.3 でビルトインSassがサポートされたようです。
https://nextjs.org/blog/next-9-3#built-in-sass-support-for-global-stylesheets

既存のBuilt-in CSSと同じ感じで、
グローバルのスタイルに加え、CSS Moduleとしても利用できるようになりました。

ビルトインなので設定なしで使用できますが、sassモジュールはインストールしましょう。

yarn add sass
# or
npm install sass

テンプレートのgit を作ったのでこちらからどうぞ。
https://github.com/itomise/next-template
sass以外のところは以下の記事を参考にしています。
https://qiita.com/syuji-higa/items/931e44046c17f53b432b

Global styles

グローバルで利用したいスタイルは、_app.tsxで~.scssのようなファイル名でインポートします。

// global style - - -
import 'sanitize.css'
import '../styles/common.scss'

class MyApp extends App {
  render(): JSX.Element {
    const { Component, pageProps }: AppProps = this.props

    return (
      <Provider store={store}>
        <Component {...pageProps} />
      </Provider>
    )
  }
}

export default MyApp

グローバルのスタイルは_app.tsxでしか適用できないようです。

Module

CSS Moduleとして使用するには、ファイル名を~.module.scssor~.module.sassにして、以下のように記述します。

import style from '../../styles/layout/Header.module.scss'

const Header: NextComponentType = () => {
  return (
    <>
      <div className={style.l_header}>
        <p>Header</p>
      </div>
    </>
  )
}

実際のクラス名は以下のようになりました。
自動で名前を変えてくれるので名前の競合もなくなりますね。
sass.PNG

post cssで autoprefixer適用

ルートにpostcss.config.jsonを置くだけでautoprefixerが適用されます。
以下のように記述すれば大丈夫なようです。

{
  "plugins": [
    "postcss-flexbugs-fixes",
    [
      "postcss-preset-env",
      {
        "autoprefixer": {
          "grid": true
        },
        "stage": 3,
        "features": {
          "custom-properties": false
        }
      }
    ]
  ]
}
8
3
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
8
3