Hiratake Web ロゴ

citty で CLI ツールをつくってみる

投稿した日
更新した日
書いたひと
icon
ひらたけ

環境

root/
 ├ bin/
 │ └ command.mjs
 ├ src/
 │ ├ cli.ts
 │ ├ command.ts
 │ └ index.ts
 ├ package.json
 └ tsconfig.json

必要なパッケージをインストールする

$ pnpm add citty
$ pnpm add -D unbuild
{
  ...
  "main": "./dist/index.cjs",
  "module": "./dist/index.mjs",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "require": "./dist/index.cjs",
      "import": "./dist/index.mjs",
      "types": "./dist/index.d.ts"
    },
    "./cli": {
      "require": "./dist/cli.cjs",
      "import": "./dist/cli.mjs",
      "types": "./dist/cli.d.ts"
    }
  },
  "bin": {
    "command": "./bin/command.mjs"
  },
  "files": ["dist", "bin"],
  "dependencies": {
    "citty": "0.1.4"
  },
  "devDependencies": {
    "unbuild": "2.0.0"
  },
  "scripts": {
    "build": "unbuild"
  }
}

コマンドを実装する

export const hoge = () => {
  console.log('fuga')
}
export * from './command'
import { defineCommand, runMain } from 'citty'
import { hoge as hogeCommand } from './command'

export const hoge = defineCommand({
  meta: { name: 'hoge' },
  run: () => hogeCommand(),
})

export const main = defineCommand({
  meta: {
    name: 'command',
    version: '1.0.0',
  },
  subCommands: { hoge },
})

export const runCommand = () => runMain(main)
#!/usr/bin/env node
import { runCommand } from '../dist/cli.mjs'
runCommand()

ビルドする

$ pnpm build
$ mkdir -p ../example
$ cd ../example
$ pnpm add [作成したCLIツールのパス]
$ pnpm [作成したCLIツールのパッケージ名] hoge