🥟

bun cli で npm scripts を同時実行したい

2024/05/01に公開

bun cli を使って package.json の scripts に記載したスクリプトを同時実行したかったので方法メモ

Issue 探し

そもそも bun cli がスクリプトの同時実行をサポートしているのかを調べるために issue を探索してこの issue を見つけました

https://github.com/oven-sh/bun/issues/4581

この issue は pnpm のように正規表現でスクリプトを並列実行したいというもので、
以下のような scripts が package.json にかかれている時

{
  "scripts": {
    "test:format": "prettier --check \"**/*.{js,ts,json,md,yml}\"",
    "test:js": "eslint \"**/*.{js,ts}\"",
    "test:types": "tsc --noEmit --pretty",
  }
}

以下みたいに実行出来たらいいよねって提案です

bun run test:*

しかしこの機能はまだサポートされていないので、以下のコメントで現状の回避策を紹介いただいてます
https://github.com/oven-sh/bun/issues/4581#issuecomment-1808892243

方法

concurrently という npm パッケージを利用する方法です
https://www.npmjs.com/package/concurrently

concurrentlynpm:<script名> の形式で package.json に書いたスクリプトを実行できます

まずはインストール

$ bun add --dev concurrently

以下のような scripts の場合、 bun run test を実行すると test:format, test:js, test:types が同時に実行されます

{
  "scripts": {
    "test": "bun run concurrently \"npm:test:*\"",
    "test:format": "prettier --check \"**/*.{js,ts,json,md,yml}\"",
    "test:js": "eslint \"**/*.{js,ts}\"",
    "test:types": "tsc --noEmit --pretty",
  }
}

ちなみに、複数指定したい場合はスペース区切りで指定すればOK

{
  "scripts": {
    "start": "bun run concurrently \"npm:format\" \"npm:js\" \"npm:types\"",
    "format": "prettier --check \"**/*.{js,ts,json,md,yml}\"",
    "js": "eslint \"**/*.{js,ts}\"",
    "types": "tsc --noEmit --pretty",
  }
}

余談

通常 bun run は bun ではなく node で実行されます

これは npm package の cli が #!/usr/bin/env node という shebang でマークされているため。
bun はこの設定を尊重してデフォルトでは node で実行してくれます

By default, Bun respects this shebang and executes the script with node.
デフォルトでは、Bun はこの shebang を尊重し、 node でスクリプトを実行する。
https://bun.sh/docs/cli/run#bun

もし bun で実行したい場合は bun run --bun concurrently のように --bun オプションをつけてあげれば bun で動きます

However, you can override this behavior with the --bun flag.
ただし、--bun フラグでこの動作をオーバーライドできる。
https://bun.sh/docs/cli/run#bun

とはいえ concurrently を bun で動かそうとすると、現状以下のようなエラーがでてしまうので大人しく node で動かしてます。。

npm ERR! p.stdin.end is not a function.

Discussion