Execute schematics-cli from oclif

Schematics is a one of the famous generator tool. It’s using in Angular / NestJS / and any other big pro […]

広告ここから
広告ここまで

目次

    Schematics is a one of the famous generator tool. It’s using in Angular / NestJS / and any other big project.

    If we want to create CLI tool with generator, we want to use Schematics within.

    So, in this posts, I try to execute schematics generator from CLI tool.

    Step1: Setup CLI project by oclif

    First, setup the example CLI project.

    Today, I used oclif.

    $ npx oclif single schematics-cli
    $ cd schematics-cli

    After the setting up, we can see the default message to execute the following command.

    $ ./bin/run 
    hello world from ./src/index.ts

    Step2: Install schematics-cli

    Next, install schematics cli library.

    We’ll execute the schematics by using it.

    $ yarn add @angular-devkit/schematics-cli

    Step3: Add schematics project

    In this post, use NestJS project

    $ yarn add @nestjs/schematics

    Of course, we can use own schematics or local schematics.

    Execute schematics-cli from oclif

    The generating process starts from the main() function in the CLI library.

    So the following code is calling the function directly.

    import {Command} from '@oclif/command'
    import {
      main
    } from "@angular-devkit/schematics-cli/bin/schematics"
    
    class SchematicsCli extends Command {
      static description = 'describe the command here'
    
      async run() {
        await main({
          args: [
              "@nestjs/schematics:interface",
              "--name=helloOclif"
          ]
      })
      }
    }
    
    export = SchematicsCli
    

    The function property is the same as the schematics CLI args.

    Execute

    Finally, execute CLI command made by oclif.

    We can get a new class file for NestJS.

    % ./bin/run
    CREATE src/hello-oclif.interface.ts (31 bytes)
    
    $ cat ./src/hello-oclif.interface.ts
    export interface HelloOclif {}

    Conclusion

    We can easy to execute schematics-cli task from own script.

    So if we want to create own CLI tools with any generator, we can use Schematics.

    [Appendix] Execute public schematics from schematics-cli

    Almost schematics project can use from their own CLI tools, like angular-cli / nest-cli / etc.

    But we can use these schematics from schematics-cli

    $ npm init -y
    $ npm i -D @angular-devkit/schematics-cli
    $ npm i -S @nestjs/schematics
    $ ./node_modules/.bin/schematics @nestjs/schematics:interface --name test
    CREATE src/test.interface.ts (25 bytes)

    広告ここから
    広告ここまで

    Random posts

    Home
    Search
    Bookmark