Lesson 8Nx create your schematics
In this section, we will create a custom schematic that permits us to generate new libraries with our specific rule (type, scope, platform)!
> npm run nx -- generate @nrwl/workspace:workspace-generator tagged-library
tools/generators/tagged-library/schema.json
{"cli": "nx","id": "tagged-library","type": "object","properties": {"name": {"type": "string","description": "Library name","$default": {"$source": "argv","index": 0}},"type": {"type": "string","description": "Type of the library","enum": ["data-access", "feature", "ui", "util"],"default": "feature","x-prompt": {"message": "What type of library is it?","items": [{"value": "data-access","label": "Data Access"},{"value": "feature","label": "Feature"},{"value": "ui","label": "Ui"},{"value": "util","label": "Util"}]}},"scope": {"type": "string","description": "Scope of the library","default": "shared","x-prompt": "What app doest this library belong to?"},"platform": {"type": "string","description": "Platform of the library","enum": ["web", "node", "any"],"default": "web","x-prompt": {"message": "What platform can this library run on?","items": [{"value": "web","label": "Web"},{"value": "node","label": "Node"},{"value": "any","label": "Any"}]}},"directory": {"type": "string","default": "","x-prompt": "What is the directory?"},"prefix": {"type": "string","default": "flw","x-prompt": "What is the Prefix?"}},"required": ["name"]}
tools/generators/tagged-library/schema.ts
export type TaggedLibrarySchemaOptions = {name: stringtype: 'data-access' | 'feature' | 'ui' | 'util'scope: 'shared' | stringplatform: 'web' | 'node' | 'any'directory?: stringprefix?: string | null}
tools/generators/tagged-library/index.ts
import { Tree, formatFiles, installPackagesTask } from '@nrwl/devkit'import { wrapAngularDevkitSchematic } from '@nrwl/devkit/ngcli-adapter'import { libraryGenerator } from '@nrwl/workspace/generators'import { libraryGenerator as backendLibraryGenerator } from '@nrwl/nest'import { TaggedLibrarySchemaOptions } from './schema'function getTags(schema: TaggedLibrarySchemaOptions): string {return `type:${schema.type},scope:${schema.scope},platform:${schema.platform}`}function getLibraryGenerator(schema: TaggedLibrarySchemaOptions) {if (schema.platform === 'node') return backendLibraryGeneratorif (schema.platform === 'web')return wrapAngularDevkitSchematic('@nrwl/angular', 'library')return libraryGenerator}export default async function (host: Tree, schema: TaggedLibrarySchemaOptions) {const libGenerator = getLibraryGenerator(schema)await libGenerator(host, { ...schema, tags: getTags(schema) })await formatFiles(host)return () => {installPackagesTask(host)}}
> npm run nx workspace-schematic tagged-library test-library