🧲

Turborepoでパッケージを公開し、公開したパッケージを利用

2023/09/17に公開

はじめに

Turborepo でパッケージを公開し、公開したパッケージを利用する方法について解説します。

この記事は以下を実施します。

  • Turborepo のプロジェクトを新規に作成
  • Internal Package(内部パッケージ)を作成
  • Internal Package(内部パッケージ)をアプリケーションで利用
  • Internal Package を External Package に変換
  • パッケージを NPM に公開
  • 公開したパッケージをアプリケーションで利用

以下の記事を参考にしています。

https://turbo.build/repo/docs/handbook/publishing-packages/versioning-and-publishing

作業コードは以下になります。

https://github.com/hayato94087/turborepo-nextjs-external-package-sample

Turborepo で作業環境を作成

create-turbo で、新規に Turborepo プロジェクトを作成します。

$ pnpm dlx create-turbo@latest

>>> TURBOREPO

>>> Welcome to Turborepo! Let's get you set up with a new codebase.

? Where would you like to create your turborepo? turborepo-nextjs-external-package-sample
? Which package manager do you want to use? pnpm workspaces

Downloading files. This might take a moment.

>>> Created a new Turborepo with the following:

apps
 - apps/docs
 - apps/web
packages
 - packages/eslint-config-custom
 - packages/tsconfig
 - packages/ui

Installing packages. This might take a couple of minutes.

>>> Success! Created a new Turborepo at "turborepo-nextjs-external-package-sample".
Inside that directory, you can run several commands:

  pnpm run build
     Build all apps and packages

  pnpm run dev
     Develop all apps and packages

  pnpm run lint
     Lint all apps and packages

Turborepo will cache locally by default. For an additional
speed boost, enable Remote Caching with Vercel by
entering the following command:

  pnpm dlx turbo login

We suggest that you begin by typing:

  cd turborepo-nextjs-external-package-sample
  pnpm dlx turbo login

プロジェクトディレクトリーに移動します。

$ cd turborepo-nextjs-external-package-sample

web アプリケーションの page.tsx を以下で上書きし、サンプルのページを作成します。

apps/web/app/page.tsx
export default function Page(): JSX.Element {
  return (
    <h1 className="text-xl">Web</h1>
  );
}

ローカルで実行します。

$ pnpm dev --filter=web

Alt text

コミットします。

$ pnpm build
$ git add .
$ git commit -m "Turborepoの初期環境を構築"

Internal Package を作成

まず、math-hekpers という名前の Internal Package を作成します。

$ mkdir packages/math-helpers

package.json を作成します。

$ touch packages/math-helpers/package.json
packages/math-helpers/package.json
{
  "name": "math-helpers",
  "main": "src/index.ts",
  "types": "src/index.ts",
  "dependencies": {
    "typescript": "latest"
  }
}

src フォルダーを作成し、packages/math-helpers/src/index.ts にて実装します。

$ mkdir -p packages/math-helpers/src
$ touch packages/math-helpers/src/index.ts
packages/math-helpers/src/index.ts
export const add = (a: number, b: number) => {
  return a + b;
};

export const subtract = (a: number, b: number) => {
  return a - b;
};

TypeScript を利用しているので、tsconfig.js を追加します。

$ touch packages/math-helpers/tsconfig.json
packages/math-helpers/tsconfig.json
{
  "compilerOptions": {
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "moduleResolution": "node",
    "preserveWatchOutput": true,
    "skipLibCheck": true,
    "noEmit": true,
    "strict": true
  },
  "exclude": ["node_modules"]
}

コミットします。

$ pnpm build
$ git add .
$ git commit -m "math-helpersを作成"

これで Internal Package は作成完了しました。

Internal Package を利用

web アプリケーションから math-helpers を利用できるように設定します。

math-helpers のパッケージを package.json に追加します。

apps/web/package.json
{
  "name": "web",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
+   "math-helpers": "workspace:*",
    "next": "^13.4.19",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "ui": "workspace:*"
  },
  "devDependencies": {
    "@next/eslint-plugin-next": "^13.4.19",
    "@types/node": "^17.0.12",
    "@types/react": "^18.0.22",
    "@types/react-dom": "^18.0.7",
    "eslint-config-custom": "workspace:*",
    "tsconfig": "workspace:*",
    "typescript": "^4.5.3"
  }
}

next.config.js の設定で、transpilePackagesmath-helpers を追加します。

apps/web/next.config.js
-module.exports = {
-  reactStrictMode: true,
-  transpilePackages: ["ui"],
-};
+/** @type {import('next').NextConfig} */
+const nextConfig = {
+ reactStrictMode: true,
+ transpilePackages: ["ui", "math-helpers"],
+};
+
+module.exports = nextConfig;

補足、上記実施しない場合のエラー

上記を実施しないと以下のようなエラーが出ます。

../../packages/math-helpers/src/index.ts
Module parse failed: Unexpected token (1:21)
You may need an appropriate loader to handle this file type,
currently no loaders are configured to process this file.
See https://webpack.js.org/concepts#loaders
> export const add = (a: number, b: number) => {
|   return a + b;
| };

webアプリケーションのパッケージをインストールします。

$ pnpm i

math-helpersをソースに追加します。

apps/web/app/page.tsx
+import { add } from "math-helpers";

export default function Page(): JSX.Element {
  return (
+   <>
      <h1 className="text-xl">Web</h1>
+     <p>1 + 2 = {add(1, 2)}</p>
+   </>
  );
 }

以下のようにエラーが表示されている場合は、TS Server / ESLint Server を再起動します。

Alt text

Alt text

ローカルで実行します。

$ pnpm dev --filter=web

Alt text

コミットします。

$ pnpm build
$ git add .
$ git commit -m "Internal Packageが利用できるように設定"

外部パッケージに変更

math-helpersを外部パッケージとして切り出します。

tsupをインストールします。tsupは、バンドルするツールです。

https://github.com/egoist/tsup

$ pnpm add tsup -D --filter=math-helpers

buildmath-helpersををバンドルします。さらに、devでは--watchを追加します。

packages/math-helpers/package.json
{
  "name": "math-helpers",
- "main": "src/index.ts",
- "types": "src/index.ts",
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "scripts": {
+   "build": "tsup src/index.ts --format cjs --dts",
+   "dev": "npm run build -- --watch"
+ },
+ "scripts": {
+   "build": "tsup src/index.ts --format cjs --dts",
+   "dev": "npm run build -- --watch"
+ },
  "dependencies": {
    "typescript": "latest"
  },
  "devDependencies": {
    "tsup": "^7.2.0"
  }
}

tsupdistディレクトリにファイルを出力します。

dist.gitignoreに追加します。

.gitignore
+# tsup
+dist

outputsdistを追加することで、distをキャッシュさせることができます。packages/math-helpersapps/webより先にビルドされる必要があります。これは、"dependsOn": ["^build"]ですでに設定されています。

turbo.json
{
  "$schema": "https://turbo.build/schema.json",
  "globalDependencies": ["**/.env.*local"],
  "pipeline": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": [
        ".next/**", 
        "!.next/cache/**", 
+       "dist/**"
      ]
    },
    "lint": {},
    "dev": {
      "cache": false,
      "persistent": true
    }
  }
}

コミットします。

$ pnpm build
$ git add .
$ git commit -m "External Packageに変更"

パッケージを公開

ここではパッケージを公開する手順を行っていきます。

Changesets の設定

Changesets CLIは、パッケージを公開するためのツールです。

https://github.com/changesets/changesets

changesetspnpmワークスペースで設定するには、changesetsdevDependency としてワークスペースのルートにインストールします。

$ pnpm add -Dw @changesets/cli --filter=math-helpers
$ cd packages/math-helpers
$ pnpm changeset init

🦋  Thanks for choosing changesets to help manage your versioning and publishing
🦋  
🦋  You should be set up to start using changesets now!
🦋  
🦋  info We have added a `.changeset` folder, and a couple of files to help you out:
🦋  info - .changeset/README.md contains information about using changesets
🦋  info - .changeset/config.json is our default config

$ cd ..

packages/math-helpers/.changesetREADMEconfig.jsonが作成されました。

スクリプトの追加

公開用のスクリプトを追加します。

packages/math-helpers/package.json
{
  "name": "math-helpers",
  "main": "src/index.ts",
  "types": "src/index.ts",
  "scripts": {
    "build": "tsup src/index.ts --format cjs --dts",
    "dev": "npm run build -- --watch",
+   "publish-packages": "turbo run build lint && changeset version && changeset publish"
  },
  "dependencies": {
    "typescript": "latest"
  },
  "devDependencies": {
    "tsup": "^7.2.0"
  }
}

publish-packagesが実行できるようにタスクをturbo.jsonに追加します。

turbo.json
{
  "$schema": "https://turbo.build/schema.json",
  "globalDependencies": ["**/.env.*local"],
  "pipeline": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": [".next/**", "!.next/cache/**", "dist/**"]
    },
    "lint": {},
    "dev": {
      "cache": false,
      "persistent": true
+    },
+   "publish-packages": {
+     "cache": false,
+     "persistent": true
    }
  }
}

package.jsonscriptspublish-packagesを追加します。

pcakage.json
{
  "private": true,
  "scripts": {
    "build": "turbo run build",
    "dev": "turbo run dev",
    "lint": "turbo run lint",
    "format": "prettier --write \"**/*.{ts,tsx,md}\"",
+   "publish-packages": "turbo run publish-packages"
  },
  "devDependencies": {
    "@changesets/cli": "^2.26.2",
    "eslint": "^8.47.0",
    "prettier": "^3.0.2",
    "tsconfig": "workspace:*",
    "turbo": "latest"
  },
  "packageManager": "pnpm@8.6.10",
  "name": "turborepo-nextjs-external-package-sample"
}

バージョンの追加

パッケージを公開するスクリプトを実行します。

$ pnpm publish-packages

versionの指定がないとエラーが出ます。

🦋  error an error occurred while publishing math-helpers: ERR_PNPM_PACKAGE_VERSION_NOT_FOUND undefined 
🦋  error {
🦋  error   "error": {
🦋  error     "code": "ERR_PNPM_PACKAGE_VERSION_NOT_FOUND",
🦋  error     "message": "Package version is not defined in the package.json."
🦋  error   }
🦋  error }
🦋  error 
🦋  error packages failed to publish:
🦋  math-helpers@undefined
 ELIFECYCLE  Command failed with exit code 1.

math-helpersにバージョンを追加します。

packages/math-helpers/package.json
{
  "name": "math-helpers",
  "main": "src/index.ts",
  "types": "src/index.ts",
+ "version": "0.0.1",
  "scripts": {
    "build": "tsup src/index.ts --format cjs --dts",
    "dev": "npm run build -- --watch",
    "publish-packages": "turbo run build lint && changeset version && changeset publish"
  },
  "dependencies": {
    "typescript": "latest"
  },
  "devDependencies": {
    "@changesets/cli": "^2.26.2",
    "tsup": "^7.2.0"
  }
}

アカウント作成

パッケージを公開するスクリプトを実行します。

$ pnpm publish-packages

アカウント作成していないとエラーが出ます。

🦋  error an error occurred while publishing math-helpers: ENEEDAUTH This command requires you to be logged in to https://registry.npmjs.org/ 
🦋  error You need to authorize this machine using `npm adduser`
🦋  error npm ERR! code ENEEDAUTH
🦋  error npm ERR! need auth This command requires you to be logged in to https://registry.npmjs.org/
🦋  error npm ERR! need auth You need to authorize this machine using `npm adduser`
🦋  error 
🦋  error npm ERR! A complete log of this run can be found in:
🦋  error npm ERR!     /Users/hayato94087/.npm/_logs/2023-08-27T03_26_37_807Z-debug-0.log
🦋  error 
🦋  error packages failed to publish:
🦋  math-helpers@0.0.1

npmのアカウントがなければアカウントを追加します。Username, Email address, Passwordを入力します。

https://www.npmjs.com/signup

アカウント追加後に、pnpm adduserを実行します。

$ pnpm adduser

 ~/Pr/turborepo-nextjs-external-package-sample/p/math-helpers  on main !5 ?1  pnpm adduser                               INT  at 12:30:20 
npm notice Log in on https://registry.npmjs.org/
Create your account at:
https://www.npmjs.com/login?next=/login/cli/c381c32b-3e432-sadfsa3-fdafas-59e07fc84b82
Press ENTER to open in the browser...

上記のリンクをクリックすると、ワンタイムパスワード画面に遷移します。

メールに送信されたワンタイムパスワードを入力します。

Alt text

EUNSCOPED

パッケージを公開するスクリプトを実行します。

$ pnpm publish-packages

restricted access とエラーが出ます。

🦋  warn No unreleased changesets found, exiting.
🦋  info npm info math-helpers
🦋  info math-helpers is being published because our local version (0.0.1) has not been published on npm
🦋  info Publishing "math-helpers" at "0.0.1"
🦋  error an error occurred while publishing math-helpers: EUNSCOPED Can't restrict access to unscoped packages. 
🦋  error npm notice Publishing to https://registry.npmjs.org/ with tag latest and restricted access
🦋  error npm ERR! code EUNSCOPED
🦋  error npm ERR! Can't restrict access to unscoped packages.
🦋  error 
🦋  error npm ERR! A complete log of this run can be found in:
🦋  error npm ERR!     /Users/hayato94087/.npm/_logs/2023-08-27T03_34_57_530Z-debug-0.log
🦋  error 
🦋  error packages failed to publish:
🦋  math-helpers@0.0.1
 ELIFECYCLE  Command failed with exit code 1.

accessを変更します。

packages/math-helpers/.changeset/config.json
{
  "$schema": "https://unpkg.com/@changesets/config@2.3.1/schema.json",
  "changelog": "@changesets/cli/changelog",
  "commit": false,
  "fixed": [],
  "linked": [],
- "access": "restricted",
+ "access": "public",
  "baseBranch": "main",
  "updateInternalDependencies": "patch",
  "ignore": []
}

パッケージ名の変更

パッケージを公開するスクリプトを実行します。

$ pnpm publish-packages

math-helpersはすでに存在しているため、エラーが出ます。

math-helpers:publish-packages: 🦋  error a package version that is forbidden by your security policy, or
math-helpers:publish-packages: 🦋  error on a server you do not have access to.
math-helpers:publish-packages: 🦋  error npm notice Publishing to https://registry.npmjs.org/ with tag latest and public access
math-helpers:publish-packages: 🦋  error npm ERR! code E403
math-helpers:publish-packages: 🦋  error npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/math-helpers - You do not have permission to publish "math-helpers". Are you logged in as the correct user?
math-helpers:publish-packages: 🦋  error npm ERR! 403 In most cases, you or one of your dependencies are requesting
math-helpers:publish-packages: 🦋  error npm ERR! 403 a package version that is forbidden by your security policy, or
math-helpers:publish-packages: 🦋  error npm ERR! 403 on a server you do not have access to.
math-helpers:publish-packages: 🦋  error 
math-helpers:publish-packages: 🦋  error npm ERR! A complete log of this run can be found in:
math-helpers:publish-packages: 🦋  error npm ERR!     /Users/hayato94087/.npm/_logs/2023-08-27T05_31_20_451Z-debug-0.log
math-helpers:publish-packages: 🦋  error 
math-helpers:publish-packages: 🦋  error packages failed to publish:
math-helpers:publish-packages: 🦋  math-helpers@0.0.1
math-helpers:publish-packages:  ELIFECYCLE  Command failed with exit code 1.

パッケージ名を変更します。

packages/math-helpers/package.json
{
- "name": "math-helpers",
+ "name": "math-helpers-20230916",
  "main": "src/index.ts",
  "types": "src/index.ts",
  "version": "0.0.1",
  "scripts": {
    "build": "tsup src/index.ts --format cjs --dts",
    "dev": "npm run build -- --watch",
    "publish-packages": "turbo run build lint && changeset version && changeset publish"
  },
  "dependencies": {
    "typescript": "latest"
  },
  "devDependencies": {
    "@changesets/cli": "^2.26.2",
    "tsup": "^7.2.0"
  }
}

Spam detection

パッケージを公開するスクリプトを実行します。

$ pnpm publish-packages

スパム検知に引っかかってしまいました。

math-helpers-20230916:publish-packages: 🦋  warn No unreleased changesets found, exiting.
math-helpers-20230916:publish-packages: 🦋  info npm info math-helpers-20230916
math-helpers-20230916:publish-packages: 🦋  warn Received 404 for npm info "math-helpers-20230916"
math-helpers-20230916:publish-packages: 🦋  info math-helpers-20230916 is being published because our local version (0.0.1) has not been published on npm
math-helpers-20230916:publish-packages: 🦋  info Publishing "math-helpers-20230916" at "0.0.1"
math-helpers-20230916:publish-packages: 🦋  error an error occurred while publishing math-helpers-20230916: E403 403 Forbidden - PUT https://registry.npmjs.org/math-helpers-20230916 - Package name triggered spam detection; if you believe this is in error, please contact support at https://npmjs.com/support 
math-helpers-20230916:publish-packages: 🦋  error In most cases, you or one of your dependencies are requesting
math-helpers-20230916:publish-packages: 🦋  error a package version that is forbidden by your security policy, or
math-helpers-20230916:publish-packages: 🦋  error on a server you do not have access to.
math-helpers-20230916:publish-packages: 🦋  error npm notice Publishing to https://registry.npmjs.org/ with tag latest and public access
math-helpers-20230916:publish-packages: 🦋  error npm ERR! code E403
math-helpers-20230916:publish-packages: 🦋  error npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/math-helpers-20230916 - Package name triggered spam detection; if you believe this is in error, please contact support at https://npmjs.com/support
math-helpers-20230916:publish-packages: 🦋  error npm ERR! 403 In most cases, you or one of your dependencies are requesting
math-helpers-20230916:publish-packages: 🦋  error npm ERR! 403 a package version that is forbidden by your security policy, or
math-helpers-20230916:publish-packages: 🦋  error npm ERR! 403 on a server you do not have access to.
math-helpers-20230916:publish-packages: 🦋  error 
math-helpers-20230916:publish-packages: 🦋  error npm ERR! A complete log of this run can be found in:
math-helpers-20230916:publish-packages: 🦋  error npm ERR!     /Users/hayato94087/.npm/_logs/2023-09-16T13_04_21_482Z-debug-0.log
math-helpers-20230916:publish-packages: 🦋  error 
math-helpers-20230916:publish-packages: 🦋  error packages failed to publish:
math-helpers-20230916:publish-packages: 🦋  math-helpers-20230916@0.0.1

パッケージ名を変更します。

packages/math-helpers/package.json
{
- "name": "math-helpers-20230916",
+ "name": "math-helpers-arithmetics",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "version": "0.0.1",
  "scripts": {
    "build": "tsup src/index.ts --format cjs --dts",
    "dev": "npm run build -- --watch",
    "publish-packages": "turbo run build lint && changeset version && changeset publish"
  },
  "dependencies": {
    "typescript": "latest"
  },
  "devDependencies": {
    "@changesets/cli": "^2.26.2",
    "tsup": "^7.2.0"
  }
}

パッケージを公開

パッケージを公開するスクリプトを実行します。

$ pnpm publish-packages

> turborepo-nextjs-external-package-sample@ publish-packages /Users/hayato94087/Private/turborepo-nextjs-external-package-sample
> turbo run publish-packages

• Packages in scope: docs, eslint-config-custom, math-lib-arithmetics, tsconfig, ui, web
• Running publish-packages in 6 packages
• Remote caching disabled
math-lib-arithmetics:publish-packages: cache bypass, force executing f68175513d7d7003
math-lib-arithmetics:publish-packages: 
math-lib-arithmetics:publish-packages: > math-lib-arithmetics@0.0.1 publish-packages /Users/hayato94087/Private/turborepo-nextjs-external-package-sample/packages/math-helpers
math-lib-arithmetics:publish-packages: > turbo run build lint && changeset version && changeset publish
math-lib-arithmetics:publish-packages: 
math-lib-arithmetics:publish-packages: • Packages in scope: math-lib-arithmetics
math-lib-arithmetics:publish-packages: • Running build, lint in 1 packages
math-lib-arithmetics:publish-packages: • Remote caching disabled
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: cache miss, executing 245778688acf5370
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: 
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: > math-lib-arithmetics@0.0.1 build /Users/hayato94087/Private/turborepo-nextjs-external-package-sample/packages/math-helpers
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: > tsup src/index.ts --format cjs --dts
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: 
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: CLI Building entry: src/index.ts
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: CLI Using tsconfig: tsconfig.json
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: CLI tsup v7.2.0
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: CLI Target: node16
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: CJS Build start
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: CJS dist/index.js 1.12 KB
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: CJS ⚡️ Build success in 213ms
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: DTS Build start
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: DTS ⚡️ Build success in 1043ms
math-lib-arithmetics:publish-packages: math-lib-arithmetics:build: DTS dist/index.d.ts 138.00 B
math-lib-arithmetics:publish-packages: 
math-lib-arithmetics:publish-packages:  Tasks:    1 successful, 1 total
math-lib-arithmetics:publish-packages: Cached:    0 cached, 1 total
math-lib-arithmetics:publish-packages:   Time:    2.987s 
math-lib-arithmetics:publish-packages: 
math-lib-arithmetics:publish-packages: 🦋  warn No unreleased changesets found, exiting.
math-lib-arithmetics:publish-packages: 🦋  info npm info math-lib-arithmetics
math-lib-arithmetics:publish-packages: 🦋  warn Received 404 for npm info "math-lib-arithmetics"
math-lib-arithmetics:publish-packages: 🦋  info math-lib-arithmetics is being published because our local version (0.0.1) has not been published on npm
math-lib-arithmetics:publish-packages: 🦋  info Publishing "math-lib-arithmetics" at "0.0.1"
math-lib-arithmetics:publish-packages: 🦋  success packages published successfully:
math-lib-arithmetics:publish-packages: 🦋  math-lib-arithmetics@0.0.1
math-lib-arithmetics:publish-packages: 🦋  Creating git tag...
math-lib-arithmetics:publish-packages: 🦋  New tag:  math-lib-arithmetics@0.0.1

 Tasks:    1 successful, 1 total
Cached:    0 cached, 1 total
  Time:    10.534s 

以下のURLでパッケージが公開されました。

https://www.npmjs.com/package/math-helpers-arithmetics

Alt text

自身の以下のページにも表示されます。

Alt text

コミットします。

$ pnpm build
$ git add .
$ git commit -m "パッケージを公開"

External Package を利用

apps/web/package.jsonを修正し、先程公開したパッケージを追加します。

apps/web/package.json
{
  "name": "web",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "^13.4.19",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "ui": "workspace:*",
-   "math-helpers": "workspace:*"
+   "math-helpers-arithmetics": "^0.0.1"
  },
  "devDependencies": {
    "@next/eslint-plugin-next": "^13.4.19",
    "@types/node": "^17.0.12",
    "@types/react": "^18.0.22",
    "@types/react-dom": "^18.0.7",
    "eslint-config-custom": "workspace:*",
    "tsconfig": "workspace:*",
    "typescript": "^4.5.3"
  }
}

パッケージをインストールします。

$ pnpm i

importを修正します。

apps/web/page.tsx
-import { add } from "math-helpers";
+import { add } from "math-helpers-arithmetics";

export default function Page(): JSX.Element {
  return (
    <>
      <h1 className="text-xl">Web</h1>
      <p>1 + 2 = {add(1, 2)}</p>
    </>
  );
}

VSCodeのエディターでエラーが出ていれば、TS Server / ESLint Server を再起動します。

Alt text

ローカルで動作確認します。

$ pnpm dev --filter=web

Alt text

コミットします。

$ pnpm build
$ git add .
$ git commit -m "外部パッケージを利用するように変更"

パッケージを更新

パッケージを更新します。ここでは、掛け算の関数、multiplyを追加します。

packages/math-helpers/src/index.ts
export const add = (a: number, b: number) => {
  return a + b;
};

export const subtract = (a: number, b: number) => {
  return a - b;
};

+export const multiply = (a: number, b: number) => {
+  return a * b;
+};

バージョンを更新します。

packages/math-helpers/package.json
{
  "name": "math-helpers-arithmetics",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
- "version": "0.0.1",
+ "version": "0.0.2",
  "scripts": {
    "build": "tsup src/index.ts --format cjs --dts",
    "dev": "npm run build -- --watch",
    "publish-packages": "turbo run build lint && changeset version && changeset publish"
  },
  "dependencies": {
    "typescript": "latest"
  },
  "devDependencies": {
    "@changesets/cli": "^2.26.2",
    "tsup": "^7.2.0"
  }
}

パッケージを公開します。

$ pnpm publish-packages

無事バージョンが0.0.2に更新されました。

Alt text

これで、apps/webmath-helpers-arithmeticsのバージョンを0.0.2に更新できます。

package.jsonを修正します。

apps/web/package.json
{
  "name": "web",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
-   "math-helpers-arithmetics": "^0.0.1",
+   "math-helpers-arithmetics": "^0.0.2",
    "next": "^13.4.19",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "ui": "workspace:*"
  },
  "devDependencies": {
    "@next/eslint-plugin-next": "^13.4.19",
    "@types/node": "^17.0.12",
    "@types/react": "^18.0.22",
    "@types/react-dom": "^18.0.7",
    "eslint-config-custom": "workspace:*",
    "tsconfig": "workspace:*",
    "typescript": "^4.5.3"
  }
}

パッケージをインストールします。

$ pnpm i

ページを修正します。

apps/web/app/page.tsx
-import { add } from "math-helpers-arithmetics";
+import { add, multiply } from "math-helpers-arithmetics";

export default function Page(): JSX.Element {
  return (
    <>
      <h1 className="text-xl">Web</h1>
      <p>1 + 2 = {add(1, 2)}</p>
+     <p>2 * 3 = {multiply(2, 3)}</p>
    </>
  );
}

ローカルで実行します。

$ pnpm dev --filter=web

Alt text

コミットします。

$ pnpm build
$ git add .
$ git commit -m "パッケージを更新し利用"

まとめ

Turborepo でパッケージを公開し、公開したパッケージを利用する方法について解説しました。

作業コードは以下です。

https://github.com/hayato94087/turborepo-nextjs-external-package-sample

参考

https://turbo.build/repo/docs/handbook/publishing-packages/versioning-and-publishing

https://www.npmjs.com/

Discussion