LoginSignup
3
1

More than 1 year has passed since last update.

Linaria のセットアップ for Next.js 13

Last updated at Posted at 2023-01-31

Motivation

Next.js 13 では新機能として App Directory が追加された。

この機能を有効化した状態での Linaria(CSS in JS ライブラリ)1 の導入手順についてまとめる。
また、Stylelint のバージョン 14 の導入方法についても併せて記載する。

Prerequisite

  • Next.js 13 がインストール済みであること(13.1.4)
  • node -v: v18.13.0
  • npm -v: 8.19.3

Setup

Linaria

必要なパッケージをインストールする:

npm install next-with-linaria @linaria/babel-preset @linaria/core @linaria/react

next.config.js に以下のような形で記載する(必要箇所だけ抜粋):

next.config.js
/** @type {import('next').NextConfig} */
const withLinaria = require('next-with-linaria');

const nextConfig = {
  // App Directory を有効化
  experimental: {
    appDir: true,
  },
  // お好みの設定を
  ..
};
module.exports = withLinaria(nextConfig);

以上となる。
以前までのバージョンよりもだいぶ簡潔な手順になっている。

ちなみに、前回まで next-linaria というパッケージを利用していたが、該当リポジトリのこの issue を見つけ、App Directory に対応したパッケージの存在を知ることになった。

Stylelint

必要なパッケージをインストールする:

npm install -D stylelint stylelint-prettier stylelint-config-prettier @stylelint/postcss-css-in-js postcss stylelint-order @linaria/stylelint-config-standard-linaria

.stylelintrc を以下のように記述する(一例):

{
  "extends": ["@linaria/stylelint-config-standard-linaria", "stylelint-prettier/recommended"],
  "overrides": [
    {
      "files": ["src/**/*.{jsx,tsx}"],
-      "customSyntax": "@stylelint/postcss-css-in-js"
    }
  ],
  "plugins": ["stylelint-order"],
  "rules": {
    "order/properties-alphabetical-order": true,
    "no-empty-source": null,
    "no-descending-specificity": null,
    "rule-empty-line-before": "never",
    "block-no-empty": null,
    "function-no-unknown": null
  }
}

2023/2/5 更新

"customSyntax": "@stylelint/postcss-css-in-js" があると、インラインスタイルを設定していると下記のようなエラーが出たため、削除した。

TypeError: Cannot read properties of undefined (reading 'includes') at ...

VSCode でファイルを保存(Cmd + S)した時にフォーマットする

extension をインストールする:

settings.json を編集する(必要箇所だけ抜粋):

settings.json
{
  ..
  "editor.codeActionsOnSave": {
    ..
    "source.fixAll.stylelint": true
  },
  "stylelint.validate": ["css", "scss", "typescriptreact"]
  ..
}

以上で、Linaria による CSS 記述部分に対して要件を満たしていないと警告がかかり、Cmd + S によりフォーマットすることができるようになった。
コマンドでフォーマットする場合は、スクリプトを追加する:

package.json
{
  "scripts": {
    ..
    "stylelint": "stylelint --fix \"**/*.{js,jsx,ts,tsx}\"" // ダブルクォートをエスケープするの忘れないでね★
  }
}

コマンドによるフォーマットは、settings.json で "editor.codeActionsOnSave.source.fixAll.stylelint": true では走らないため注意

  1. Next.js 11 での Linaria 導入についてはこの記事にまとめている

3
1
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
3
1