Categories
Uncategorized

Create Schematic using Schematic-CLI from angular-devkit

We can easily create a new schematic which we can use with the help of Angular-CLI in few minutes. Install the required package globally using npm as shown below. You will need node version >= 6.9 for this.

npm i -g @angular-devkit/schematics-cli

Now create a blank schematics project and switch to that directory.

schematics blank --name=new-component
cd new-component
npm i

Navigate to new-component/index.tsĀ and add the following code.

index.ts

import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';

const fileName = 'myfile';
const fileContent = `
Hello World!
`;

// You don't have to export the function as default. You can also have more than one rule factory
// per file.
export function myComponent(options: any): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    tree.create(options.name || fileName, fileContent);
    return tree;
  };
}

Build & Publish

Navigate to the root of your project and use the following commands.

npm run build
schematics .:new-component --name=somename
npm publish
// you will be prompted to do 'npm adduser' if your account isn't setup

Link & Install

You can do an npm link to link the schematics project locally to a new angular application created by angular-cli or you can use npm installĀ to add it to your project from remote.

Help

To learn how to use the schematics-cli tool, you can refer to the help command as follows.

schematics --help
schematics [CollectionName:]SchematicName [options, ...]

By default, if the collection name is not specified, use the internal collection provided
by the Schematics CLI.

Options:
    --debug             Debug mode. This is true by default if the collection is a relative
                        path (in that case, turn off with --debug=false).
    --dry-run           Do not output anything, but instead just show what actions would be
                        performed. Default to true if debug is also true.
    --force             Force overwriting files that would otherwise be an error                                            .
    --list-schematics   List all schematics from the collection, by name.
    --verbose           Show more information.

    --help              Show this message.

Any additional option is passed to the Schematics depending on