npmでCLIを配布するならシェバンを忘れずに

先日、「MarkdownをSlackでコピペするためにいい感じに変換するCLI mdjanai」をnpmで公開しました(紹介記事)。

筆者が最初に公開したときにshebangを付け忘れてエラーになっていたので今回はその備忘録です。

エラーは静かに終わる

実際にコマンドを実行したら何も表示されずに異常終了しました。

原因

筆者は動作確認のときに次のようにnodeで実行していました。

Terminal window
node dist/index.js

これなら当然nodeで実行されます。ただ、実際にCLIが実行される時はindex.jsが直接実行されるのでshebangが必要です。

対応

というわけでファイル冒頭にshebangを付けました。

src/index.ts
#!/usr/bin/env node
import { foo } from "./foo"
// ...

どういうエラーが出たのか

修正前に 手元でビルドしたやつを、nodeではなくファイルを直接実行してみます。

Terminal window
./dist/index.js
dist/index.js: line 1: import: command not found
dist/index.js: line 2: import: command not found
dist/index.js: line 3: import: command not found
dist/index.js: line 4: import: command not found
dist/index.js: line 5: import: command not found
dist/index.js: line 6: import: command not found
dist/index.js: line 7: import: command not found
dist/index.js: line 8: import: command not found
dist/index.js: line 9: import: command not found
dist/index.js: line 10: import: command not found
dist/index.js: line 12: //#region: No such file or directory
dist/index.js: line 13: var: command not found
dist/index.js: line 15: //#endregion: No such file or directory
dist/index.js: line 16: //#region: No such file or directory
dist/index.js: line 17: syntax error near unexpected token `('
dist/index.js: line 17: `const execFilePromise$1 = promisify(execFile);'

command not foundNo such file or directoryがずらずら出ます。というわけでshebang忘れないようにしましょう。


以上、Node.jsで書いたCLIをnpmで配布するならshebang忘れないで、という備忘録でした。