LoginSignup
2
2

More than 1 year has passed since last update.

【Docker】Yarn v3を使用する【React】【Next.js】

Last updated at Posted at 2022-05-02

Yarn v3を使用する

DockerでYarn v3を使用するNext.jsの環境を構築する方法について記載します。
Next.jsで記載しますがReactでもほとんど同じです。

コンテナ起動の準備をする

まず、Dockerfiledocker-compose.ymlを作成します。
それぞれ以下のようにします。

Dockerfile
FROM node:16.15.0

ENV USER_NAME=myuser
ENV TZ=Asia/Tokyo

WORKDIR /myapp

USER ${USER_NAME}

EXPOSE 3000
CMD ["yarn", "dev"]
docker-compose.yml
version: '3.9'
services:
  front:
    build: .
    volumes:
      - .:/myapp
    environment:
      NODE_ENV: development
    ports:
      - 3000:3000

Yarnのバージョンを変更する

Dockerfiledocker-compose.ymlを作成すればコンテナを起動できます。
ターミナルでdocker compose run front bashを実行します。

ターミナル
$ docker compose run front bash

コンテナが起動したらコンテナ内でyarn init -2を実行します。

ターミナル
myuser@rs6437j9n45a:/myapp$ yarn init -2

すると下画像のようにファイルが作成されます。
image220502_172124.png

試しにyarn -vを実行します。

ターミナル
myuser@2246ae8aafde:/myapp$ yarn -v
3.2.0

Yarnのバージョンが3.2.0になっています。

.yarnrc.ymlを編集する

yarn init -2で作成されたファイルのうち.yarnrc.ymlを編集します。
以下のように記述します。

.yarnrc.yml
yarnPath: .yarn/releases/yarn-3.2.0.cjs
cacheFolder: "/myapp/.yarn/cache"

上記のうちyarnPathyarn init -2を実行すると記述されます。
cacheFolderにはコンテナ側のcacheへのパスを記述します。
これを記述しておくとホスト側でyarn addなどをしてしまっても以下のようなエラーが出ます。

ターミナル
$ yarn add <package>
Internal Error: ENOENT: no such file or directory, mkdir '/myapp'
Error: ENOENT: no such file or directory, mkdir '/myapp'

ホスト側でyarn addを実行するとエラーの原因となることがあります。
詳細については以下の記事をご参照ください。

package.jsonを編集する

package.jsonを以下のように変更します。

package.json
{
  "workspaces": [
    "/myapp/*"
  ]
}

ワークスペースの設定をしています。
パスはコンテナ側のパスを記述します。
これがないとcreate-next-appした際に以下のようなエラーが出ます。

ターミナル
Usage Error: The nearest package directory (/myapp/app_name) doesn't seem to be part of the project declared in /myapp.

- If /myapp isn't intended to be a project, remove any yarn.lock and/or package.json file there.
- If /myapp is intended to be a project, it might be that you forgot to list app_name in its workspace configuration.
- Finally, if /myapp is fine and you intend app_name to be treated as a completely separate project (not even a workspace), create an empty yarn.lock file in it.

TypeScriptを使用する場合

TypeScriptを使用する場合には以下のコマンドを実行します。

ターミナル
myuser@2246ae8aafde:/myapp$ yarn plugin import typescript

実行すると下画像のようにファイルが追加されます。

image220502_181232.png

プラグインの詳細については以下をご参照ください。

ファイルを整理する

create-next-appした際に上書きされてしまうファイルがあるので削除します。
削除するのが面倒な場合はそのままでも問題はありません。
ただし.gitignoreの内容についてはのちほど使用するため別のディレクトリに移すなどしてください。
削除するファイルは以下のとおりです。

  • .gitignore (内容はのちほど使用します。)
  • README.md
  • yarn.lock

上記を削除すると以下のようになります。
image220502_185559.png

create-next-appする

コンテナ内にいる場合にはexitで抜けます。

ターミナル
myuser@2246ae8aafde:/myapp$ exit

ホスト側で以下を実行します。

ターミナル
$ docker compose run --rm front yarn create next-app --ts app_name && \
  cd $_ && \
  mv * .* .. && \
  rmdir $(pwd) && \
  cd ../ && \
  docker compose run --rm front sh -c "yarn install && yarn dlx @yarnpkg/sdks vscode"

カレントディレクトリに展開するため、上記のように実行しています。
また上記のように記述するとapp_nameの箇所のみ変更すれば別のプロジェクトでも対応できます。

ワークスペースを/myapp/*と設定したため、ここでyarn installをしないとdocker compose upした際に以下のようなエラーが出ます。

ターミナル
$ docker compose up
[+] Running 1/1
 ⠿ Container next-yarnv3-front-1  Created                  0.1s
Attaching to next-yarnv3-front-1
next-yarnv3-front-1  | Internal Error: Assertion failed: Expected workspace yarn-test (/myapp/package.json) to have been resolved. Run "yarn install" to update the lockfile
next-yarnv3-front-1  |     at ze.refreshWorkspaceDependencies (/myapp/.yarn/releases/yarn-3.2.0.cjs:441:3811)
next-yarnv3-front-1  |     at ze.restoreInstallState (/myapp/.yarn/releases/yarn-3.2.0.cjs:447:1240)
next-yarnv3-front-1  |     at processTicksAndRejections (node:internal/process/task_queues:96:5)
next-yarnv3-front-1  |     at async xm.execute (/myapp/.yarn/releases/yarn-3.2.0.cjs:574:1879)
next-yarnv3-front-1  |     at async xm.validateAndExecute (/myapp/.yarn/releases/yarn-3.2.0.cjs:349:673)
next-yarnv3-front-1  |     at async Is.run (/myapp/.yarn/releases/yarn-3.2.0.cjs:363:2087)
next-yarnv3-front-1  |     at async GN.execute (/myapp/.yarn/releases/yarn-3.2.0.cjs:474:531)
next-yarnv3-front-1  |     at async GN.validateAndExecute (/myapp/.yarn/releases/yarn-3.2.0.cjs:349:673)
next-yarnv3-front-1  |     at async Is.run (/myapp/.yarn/releases/yarn-3.2.0.cjs:363:2087)
next-yarnv3-front-1  |     at async Is.runExit (/myapp/.yarn/releases/yarn-3.2.0.cjs:363:2271)
next-yarnv3-front-1 exited with code 1

yarn dlx @yarnpkg/sdks vscodeについてはVSCode用の設定を生成するために実行しています。
実行するコマンドはエディタごとに異なります。
詳細については以下をご参照ください。

コマンドを実行するだけでは不十分で設定を明示的に有効にする必要があります。
有効にする方法については後述します。

現時点でファイルは以下のようになっています。
image220502_182532.png

.gitignoreを編集する

.gitignoreyarn init -2で作成された.gitignoreの内容を反映します。
# dependenciesを以下のようにします。

.gitignore
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
!.yarn/cache

<以下略>

npm installできないようにする

Yarnを使用するため、npm installできないようにします。
npm installを使用不可にする方法は以下の記事にまとめています。

上記の記事に記載しているため、簡単に記載します。

package.json
{
  "engines": {
    "npm": "npmではなくyarnを使用してください"
  }
}
.npmrc
engine-strict=true

またpackage.jsonに以下を追記し、Corepackを有効化することでpnpmの使用を制限できます。

package.json
{
  "packageManager": "yarn@3.2.0"
}

Corepackを有効化するには以下のコマンドを実行します。

ターミナル
$ corepack enable

packageManagerの箇所に設定したパッケージマネージャが使用されるようになります。
そのほかのパッケージマネージャを使用するとエラーが出ます。
packageManagerを上記のように記述した状態でpnpmを使用するとエラーが出ます。
しかし、npmは使用できてしまいます。
npmでもエラーが出るようにするためには。corepack enable npmを実行する必要があります。
またバージョンの管理もできますが、Yarnのバージョンはyarn init -2を実行した段階で固定されています。
そのため、packageManagerを変更してもバージョンの変更はできません。
バージョン変更はyarn set version <version>で行います。

VSCodeを設定する

前述したとおりVSCodeの設定についてyarn dlx @yarnpkg/sdks vscodeを実行するだけでは不十分です。
設定を明示的に有効にする必要があります。

VSCodeを開き、TypeScriptのファイルを開きます。
cmd + sft + pを入力します。
image220502_194049.png
表示された入力欄にSelect TypeScript Versionと入力しEnterを入力します。
すると下画像のように表示されるのでワークスペースのバージョンを使用をクリックします。
image220502_194224.png
ワークスペースのバージョンを使用が表示されない場合にはVSCodeを開き直してください。

docker compose upする

docker compose upして正常に起動するか確認します。

ターミナル
$ docker compose up

エラーなく起動したら http://localhost:3000/ を確認します。

以下のように表示されたらOKです。

image220502_212210.png

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