3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next.jsのプロジェクトににMUIを導入する

Posted at

はじめに

Next.jsにMUIを導入する方法が書かれた記事はたくさんありますが、MUIやyarnのバージョンによっては動かないことがあるため記事にしました。
今回はMUI v5.12.3のExampleを参考にしましたが、yarn v3では動かない箇所があるため改良を加えています。

使用したライブラリとバージョン

ライブラリ バージョン
next 13.3.4
@emotion/cache 11.10.8
@emotion/react 11.10.8
@emotion/server 11.10.0
@emotion/styled 11.10.8
@mui/icons-material 5.11.16
@mui/material 5.12.3

手順

1. Next.jsのプロジェクトを作成する

MUIとtailwind cssをそのまま併用すると背景や文字色が干渉するため無効にします。
今回は分かりやすいように --src-dirを使いましたが、無くても大丈夫です。
また、2023年5月現在、MUI側がapp directoryに対応していないようなので、--no-experimental-appを付けています。

corepack yarn create next-app "[プロジェクト名]" --src-dir --ts --eslint --import-alias "@/*" --no-tailwind --no-experimental-app

今回はyarn v3を使用しました。

corepack yarn set version berry
# 初回のインストールで"Migrating from Yarn 1"を済ませておく
corepack yarn install
# nodeLinkerの設定を削除
sed -i 's/^nodeLinker/# nodeLinker/' .yarnrc.yml
# 再度パッケージをインストールすることで、node_modulesフォルダを削除
corepack yarn install

2. MUIをインストールする

MUI公式のGetting Startedに従い、以下をインストールします。

yarn add @mui/material @emotion/react @emotion/styled
# アイコンを使用する場合は以下もインストールする
yarn add @mui/icons-material

Next.jsでSSRを行うために、下記をインストールします。

yarn add @emotion/server @emotion/cache

ただし、yarn berryでない環境では@emotion/cacheは自動でインストールされるようです。

3. MUIをNext.jsプロジェクトに組み込む

  1. 公式のExampleからtheme.tstheme.ts_app.tsx_document.tsxをプロジェクトにコピーし、以下のように配置します。
    .
    |- src/
    |  |- lib/
    |  |  |- createEmotionCache.ts
    |  |  \- theme.ts
    |  |- pages/
    |  |  |- _app.tsx
    |  |  |- _document.tsx
    :  :  :
    
  2. pages/_app.tsxpages/_document.tsxにあるimport元を書き換えます。
    • プロジェクトを作成したときにパスのaliasを指定してある場合は、../src/…@/…に置き換えるだけで大丈夫です。

おわり

公式のExampleをコピーするだけなのでわざわざ記事にするほどでもないと思いましたが、公式Exampleにあるtheme.tsnext/fontを活用していたりとお手本のような感じだったので、周知も兼ねて記事にしました。
おそらくcreate-next-appのオプションに公式ExampleのURLを付ける方がメジャーなやり方だと思いますが、デフォルトでパッケージのバージョンが明記されていないなど再現性に欠けるため今回は採用しませんでした。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?