Nest.js Command tools, base on yargs
- Use version
1.*for nestjs6.* - Use version
0.*for nestjs5.*
$ npm install --save nestjs-command
# if use typescript
$ npm install --save-dev @types/yargsRegister the command module in base module: /src/app.module.ts
import{Module}from'@nestjs/common';import{CommandModule}from'nestjs-command';
@Module({imports: [CommandModule,],})exportclassAppModule{}Create a Init File: /src/cli.ts
import{NestFactory}from'@nestjs/core';import{CommandModule,CommandService}from'�nestjs-command';import{CoreModule}from'./core/core.module';(async()=>{constapp=awaitNestFactory.createApplicationContext(CoreModule,{logger: false// no logger});app.select(CommandModule).get(CommandService).exec();})();Create cli file: /bin/cli
Use nestjs-command to exec command (instead /bin/cli)
npx nestjs-command: run by default/src/cli.tsCLI_PATH=./dist/cli.js npx nestjs-command: run/dist/cli.jsby envCLI_PATH
Create a simple Command File: /src/user/user.command.ts
import{Command,Positional}from'nestjs-command';import{Injectable}from'@nestjs/common';import{UserService}from'./user.service';
@Injectable()exportclassUserCommand{constructor(privatereadonlyuserService: UserService,){}// autoExit defaults to `true`, but you can use `autoExit: false` if you need more control
@Command({command: 'create:user <account>',describe: 'create a user',autoExit: true})asynccreate(
@Positional({name: 'account',describe: 'the user account string',type: 'string',})account: string,){constuser=awaitthis.userService.create(account);console.log(user);}}Register UserCommand class as provider in base module: /src/app.module.ts
import{Module}from'@nestjs/common';import{CommandModule}from'nestjs-command';import{UserCommand}from"./user/user.command";
@Module({imports: [CommandModule,],providers: [UserCommand]})exportclassAppModule{}Run cli in terminal
npx nestjs-command create:user my-first-user