node.jstypescriptnode-commander

How to use commander to generate command


I am working on a cli tool with commander. I have this app.ts file.

import { Command } from 'commander';
const program = new Command();
program.version('0.0.1');

const zoneConf = program.command('zone-conf');
const generate = zoneConf.command('generate');
generate.command('tx-commands').action(() => {
    console.log('Ran `zone-conf generate tx-commands`');
});

program.parse(process.argv);

I expect that when I run tsc && node app.js, I would be able to do run a command like zone-conf generate tx-commands. When I do run it the output is zsh: command not found: zone-conf.

Is therw a step I am missing with commander in nodejs.


Solution

  • For your terminal to recognize your command you can use npm link. Which will create a global link for your package.

    You should first build your application and then run the link command.

    In your project folder run:

    $ tsc
    $ npm link
    

    If this is not something you want to leave it linked, after you are done using it, you can use the npm uninstall to remove it:

    $ npm uninstall -g <your-package-name>
    

    If you don't want to link it globally, the comment from @shadowspawn should work:

    tsc && node app.js zone-conf generate tx-commands