LoginSignup
2
2

More than 3 years have passed since last update.

自己紹介のnpxコマンド作ってみた

Posted at

モチベーション

npm配信で型,hooks,コンポーネントと経験したので、npxで動かすようなコマンドを作ってみたかった

が特にネタがなかったので、流行りの自分の名前のREAD.MEから思いついた

index.ts
#!/usr/bin/env node
// ↑binで呼ばれる時にnodeで動かして欲しいので書く
const help = () => console.log(`
Usage: kodai3 <command>
where <command> is one of:
    help       what you see now
    ...
`)

const argv = process.argv.slice(2);
// 今回引数は一つしか対応しないので
if (argv.length !== 1) {
    help();
    process.exit(0);
}

switch (argv[0].toLocaleLowerCase()) {
    case 'help':
        help();
        process.exit(0);

    ...

    default:
        help();
        process.exit(0);
}
package.json
{
 "main": "dist/index.js",
 "bin": {
     "kodai3": "dist/index.js",
 },
 "scripts": {
     "build": "yarn tsc",
 }
}

binが重要
install時に.bin以下にkeyで指定したコマンド名でスクリプトを作成してくれる
tscで普通にcommonjsにしてpublishする

npx kodai3 whoami

注意

npmで配信すると、72時間以上立ったものは基本的に停止できなくなるのでセンシティブな情報は入れてはいけない
(snsアカウントはいっかと思って自分は入れた)

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2