Angular Schematics is a powerful tool that allows you to generate components, services, directives, and more with a simple command. Angular Builders, on the other hand, are responsible for transforming your source code into an executable JavaScript bundle that runs in the browser. Together, Schematics and Builders can be used to create custom workflows, automate repetitive tasks, and overall improve developer productivity.
To effectively use Angular Schematics and Builders, follow these steps:
1. **Create Custom Schematic Collection:**
First, you need to create a custom schematic collection:
ng new schematic --name=my-schematics
cd my-schematics
npm run build
This will create a new schematic project with a sample schematic named "my-schematics".
2. **Implement Custom Schematics:**
Now let’s create a custom schematic for generating a new Angular service with a predefined structure. To do this, create a new folder "my-service" inside the "src" folder and add the following files:
- ‘index.ts‘: Main Schematic file
- ‘schema.json‘: Defines the input parameters for the Schematic
- ‘files‘: A template folder containing a service file with the desired structure
Here’s an example of the ‘index.ts‘ file:
import {
Rule,
SchematicContext,
SchematicsException,
Tree,
apply,
chain,
mergeWith,
template,
url,
} from '@angular-devkit/schematics';
import { strings } from '@angular-devkit/core';
// Custom Schema for the Schematic
interface MyServiceOptions {
name: string;
path?: string;
}
export function myService(options: MyServiceOptions): Rule {
return (tree: Tree, _context: SchematicContext) => {
// Get the input options
const name = options.name;
const path = options.path || '';
// Verify inputs
if (!name) {
throw new SchematicsException('Option "name" is required.');
}
// Create and apply the template
const templateSource = apply(url('./files'), [
template({ ...options, ...strings }), // Provide string utilities from @angular-devkit/core
]);
// Add the service to the provided path
return chain([mergeWith(templateSource)])(tree, _context);
};
};
And an example of ‘schema.json‘ file:
{
"$schema": "http://json-schema.org/schema",
"id": "my-service",
"title": "My Service Schematic",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the service"
},
"path": {
"type": "string",
"description": "The path where the service will be generated"
}
},
"required": [
"name"
]
}
Finally, in ‘collection.json‘, add the custom schematic:
{
"schematics": {
"my-service": {
"description": "A custom schematic that generates a service with a predefined structure",
"factory": "./my-service/index#myService",
"schema": "./my-service/schema.json"
}
}
}
3. **Create Custom Builders:**
To create a custom builder, first, create a new folder "my-builder" inside the "src" folder and add a new TypeScript file ‘index.ts‘:
import {
BuilderContext,
BuilderOutput,
createBuilder,
} from '@angular-devkit/architect';
interface Options {
// Define any custom options for the builder here
}
// The custom builder function
async function myBuilder(
options: Options,
context: BuilderContext
): Promise<BuilderOutput> {
// Implement the custom build process here
// Return a successful result
return { success: true };
}
// Export your custom builder
export default createBuilder(myBuilder);
Next, update the ‘builders.json‘ file in the same folder to add the custom builder:
{
"builders": {
"my-builder": {
"implementation": "./src/my-builder/index",
"schema": "./src/my-builder/schema.json",
"description": "A custom builder"
}
}
}
Don’t forget to add the schema file ‘schema.json‘:
{
"$schema": "http://json-schema.org/schema",
"id": "my-builder",
"type": "object",
"properties": {
// Define your custom options for the builder here
},
"additionalProperties": false
}
4. **Use the Custom Schematic and Builder:**
To use the custom schematic, first, build the schematic project:
npm run build
Then, link the schematic to make it available for the Angular CLI:
npm link
Now, you can use the custom schematic with the Angular CLI like this:
ng generate my-schematics:my-service --name=my-new-service
This will generate a new service based on the predefined structure.
To use custom builders, update the ‘angular.json‘ file in your main Angular project to include the custom builder:
{
"architect": {
"build": {
"builder": "my-schematics:my-builder",
"options": {
// Specify your custom options here
}
}
}
}
Now, you can use the custom builder by running:
ng build
These are just simple examples for illustration purposes. You can create more sophisticated schematics and builders to streamline your development process, automate tasks, and save time.
By effectively utilizing Angular Schematics and Builders, you can create custom workflows, automate repetitive tasks, and improve developer productivity throughout your project.