[Next.js] Emotion SWC有効する方法

3 min read
hiroweb developer

概要

Next.js v12.1.1-canary.12 で Emotion の SWC 対応が入った(v12.1.1 から正式に入るだろう)。

https://github.com/vercel/next.js/pull/34687

追記

Next.js v12.2にて Next.js Compiler での Emotion transform がサポートされた。

方法

  1. Babel の設定ファイル(babel.config.jsなど)を削除
    ※ Emotion 以外の設定がある場合は削除してしまうと問題
  2. @emotion/babel-pluginをアンインストール
  3. ドキュメントの設定をnext.config.jsに追加する
// next.config.js

module.exports = {
  compiler: {
    emotion: boolean | {
      // デフォルトはtrue。ビルドタイプがproductionの場合は無効となります。
      sourceMap?: boolean,
      // デフォルトは'dev-only'.
      autoLabel?: 'never' | 'dev-only' | 'always',
      // デフォルトは'[local]'.
      // 許容値: `[local]` `[filename]` and `[dirname]`
      // このオプションは、autoLabel が 'dev-only' または 'always' に設定されているときのみ機能します。
      // 生成されるラベルの形式を定義でます。
      // フォーマットは文字列で定義され、変数部分は角括弧 [] で囲まれる。
      // 例)labelFormat: "my-classname--[local]", ここで[local]は結果が代入される変数の名前に置き換えられる。
      labelFormat?: string,
      // デフォルトは undefined.
      // このオプションは、コンパイラがどの import を見て何を変換するかを指定する
      // Emotion のエクスポートを再出力した場合でも、transform を使用することができる
      importMap?: {
        [packageName: string]: {
          [exportName: string]: {
            canonicalImport?: [string, string],
            styledBaseImport?: [string, string],
          }
        }
      },
    },
  },
}

Only importMap in @emotion/babel-plugin is not supported for now.

importMapは未対応とのこと。

importMapは未対応だったが、後日対応された。

その他

自環境では問題なかったが、コードによってはうまく動かないケースもあるみたいですので、正式リリース時には解消されていることを願う。

github.comPort @emotion/babel-plugin to SWC · Issue #30804 · vercel/next.jsThis plugin is being used by a good chunk of users. #30802 has even more users though so it's best to start with that one.