🎉

✍️ AWS CodeBuildでYarn Berry(v4)を使う

に公開

AWS CodeBuildでYarn Berry(v4以降、今回はv4.9.2)を使用する際のポイントをまとめたメモです。


✨ Yarn v4 を CodeBuild で使う背景

Yarn v4(Berry)は高速な依存関係解決やPnP(Plug'n'Play)機能などを提供する一方、従来の node_modules ベースと互換性がやや異なるため、CI環境でのセットアップに注意が必要です。


⚙️ Yarn のバージョン指定方法

✅ 安定版(最新の安定版)を使いたい場合

corepack enable
corepack prepare yarn@stable --activate

この場合、常に Yarn の最新安定バージョンが使用されます(例: 4.x 系の最新)。

✅ 特定のバージョン(例: v4.9.2)を固定したい場合

corepack enable
corepack prepare yarn@4.9.2 --activate

この方法なら、ローカルとCIで Yarn のバージョンがずれることを防げます。


⚡ buildspec.yml の設定例(Yarn v4.9.2 + node_modules モード)

version: 0.2

phases:
  install:
    runtime-versions:
      nodejs: 18
    commands:
      - corepack enable
      - corepack prepare yarn@4.9.2 --activate
      - yarn --version
      - yarn install --immutable

  build:
    commands:
      - yarn build

artifacts:
  files:
    - dist/**/*

📘 .yarnrc.yml の設定例

nodeLinker: node-modules
  • pnp モードだと CodeBuild や一部ライブラリとの互換性問題が出るため、node-modules を使用。
  • yarnPath を使う場合は .yarn/releases.cjs ファイルを置き、Git 管理が必要。

‼️ 注意点とハマりどころ

内容 解説
--immutable-cache .yarn/cache を Git 管理していないとエラーになります
.yarn/cache --immutable-cache を使うなら必須。今回は使わないので不要
corepack の有効化 Node.js 16.10+ に同梱されているので corepack enable でOK

🏗 CDK Pipeline での CodeBuild 設定

CDKで CodeBuildStep を使ってパイプラインに組み込む場合は、以下のようにします。

import { CodeBuildStep } from 'aws-cdk-lib/pipelines';

new CodeBuildStep('Synth', {
  input: myGitSource,
  installCommands: [
    'corepack enable',
    'corepack prepare yarn@4.9.2 --activate', // または yarn@stable
    'yarn install --immutable',
  ],
  commands: [
    'yarn build',
    'npx cdk synth',
  ],
});

📅 まとめ

  • Yarn v4 を使う場合は Corepack でバージョン管理が推奨
  • 安定版を使うなら yarn@stable特定バージョンを固定するなら yarn@4.9.2
  • --immutable は有効だが --immutable-cache.yarn/cache を Git 管理してないなら使わないこと
  • nodeLinker: node-modules の設定で互換性を確保
  • CDK Pipeline でも installCommandscorepack の操作と yarn install を入れればOK

今後、Yarn v4 系を CI/CD に組み込む際のトラブルを避けるための参考になれば幸いです ✨

Discussion