Socket
Socket
Sign inDemoInstall

@angular-devkit/schematics

Package Overview
Dependencies
5
Maintainers
2
Versions
742
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

@angular-devkit/schematics


Version published
Maintainers
2
Created

Package description

What is @angular-devkit/schematics?

@angular-devkit/schematics is a powerful tool for creating and managing code transformations in Angular projects. It allows developers to automate tasks such as generating components, services, and other Angular constructs, as well as performing code modifications and migrations.

What are @angular-devkit/schematics's main functionalities?

Generating a Component

This feature allows you to generate a new Angular component by creating the necessary TypeScript file with a basic component structure.

const { Rule, SchematicContext, Tree } = require('@angular-devkit/schematics');

function createComponent(options) {
  return (tree, _context) => {
    const content = `import { Component } from '@angular/core';

@Component({
  selector: 'app-${options.name}',
  templateUrl: './${options.name}.component.html',
  styleUrls: ['./${options.name}.component.css']
})
export class ${options.name.charAt(0).toUpperCase() + options.name.slice(1)}Component { }
`;
    tree.create(`/src/app/${options.name}/${options.name}.component.ts`, content);
    return tree;
  };
}

module.exports = { createComponent };

Updating a File

This feature allows you to update an existing file by replacing specified text with new text.

const { Rule, SchematicContext, Tree } = require('@angular-devkit/schematics');

function updateFile(options) {
  return (tree, _context) => {
    const filePath = options.path;
    if (tree.exists(filePath)) {
      const content = tree.read(filePath).toString('utf-8');
      const updatedContent = content.replace(options.oldText, options.newText);
      tree.overwrite(filePath, updatedContent);
    }
    return tree;
  };
}

module.exports = { updateFile };

Deleting a File

This feature allows you to delete a specified file from the project.

const { Rule, SchematicContext, Tree } = require('@angular-devkit/schematics');

function deleteFile(options) {
  return (tree, _context) => {
    const filePath = options.path;
    if (tree.exists(filePath)) {
      tree.delete(filePath);
    }
    return tree;
  };
}

module.exports = { deleteFile };

Other packages similar to @angular-devkit/schematics

Readme

Source

Schematics

A scaffolding library for the modern web.

Description

Schematics are generators that transform an existing filesystem. It can create files, refactor existing files, or move files around.

What distinguish Schematics from other generators, such as Yeoman or Yarn Create, is that schematics are purely descriptive; no changes are applied to the actual filesystem until everything is ready to be committed. There is no side effect, by design, in Schematics.

Glossary

TermDescription
SchematicsA generator that execute descriptive code without side effects on an existing file system.
CollectionA list of schematics metadata. Schematics can be referred by name inside a collection.
ToolThe code using the Schematics library.
TreeA staging area for changes, containing the original file system, and a list of changes to apply to it.
RuleA function that applies actions to a Tree. It returns a new Tree that will contain all transformations to be applied.
SourceA function that creates an entirely new Tree from an empty filesystem. For example, a file source could read files from disk and create a Create Action for each of those.
ActionA atomic operation to be validated and committed to a filesystem or a Tree. Actions are created by schematics.
SinkThe final destination of all Actions.

Tooling

Schematics is a library, and does not work by itself. A reference CLI is available on this repository, but is not published on NPM. This document explain the library usage and the tooling API, but does not go into the tool implementation itself.

The tooling is responsible for the following tasks:

  1. Create the Schematic Engine, and pass in a Collection and Schematic loader.
  2. Understand and respect the Schematics metadata and dependencies between collections. Schematics can refer to dependencies, and it's the responsibility of the tool to honor those dependencies. The reference CLI uses NPM packages for its collections.
  3. Create the Options object. Options can be anything, but the schematics can specify a JSON Schema that should be respected. The reference CLI, for example, parse the arguments as a JSON object and validate it with the Schema specified by the collection.
  4. Schematics provides some JSON Schema formats for validation that tooling should add. These validate paths, html selectors and app names. Please check the reference CLI for how these can be added.
  5. Call the schematics with the original Tree. The tree should represent the initial state of the filesystem. The reference CLI uses the current directory for this.
  6. Create a Sink and commit the result of the schematics to the Sink. Many sinks are provided by the library; FileSystemSink and DryRunSink are examples.
  7. Output any logs propagated by the library, including debugging information.

The tooling API is composed of the following pieces:

Engine

The SchematicEngine is responsible for loading and constructing Collections and Schematics'. When creating an engine, the tooling provides an EngineHost interface that understands how to create a CollectionDescription from a name, and how to create a SchematicDescription.

Schematics (Generators)

Schematics are generators and part of a Collection.

Collection

A Collection is defined by a collection.json file (in the reference CLI). This JSON defines the following properties:

Prop NameTypeDescription
namestringThe name of the collection.
versionstringUnused field.

Schematic

Operators, Sources and Rules

A Source is a generator of Tree; it creates a root tree from nothing. A Rule is a transformation from one Tree to another. A Schematic (at the root) is a Rule that is normally applied on the filesystem.

Operators

FileOperators apply changes to a single FileEntry and return a new FileEntry. The result follows these rules:

  1. If the FileEntry returned is null, a DeleteAction will be added to the action list.
  2. If the path changed, a RenameAction will be added to the action list.
  3. If the content changed, an OverwriteAction will be added to the action list.

It is impossible to create files using a FileOperator.

FileOperatorDescription
contentTemplate<T>(options: T)Apply a content template (see the Template section)
pathTemplate<T>(options: T)Apply a path template (see the Template section)

Provided Sources

The Schematics library provides multiple Source factories by default that cover basic use cases:

SourceDescription
source(tree: Tree)Creates a source that returns the tree passed in argument.
empty()Creates a source that returns an empty tree.
apply(source: Source, rules: Rule[])Apply a list of rules to a source, and return the result.
url(url: string)Loads a list of files from a URL and returns a Tree with the files as CreateAction applied to an empty Tree

Provided Rules

The schematics library also provides Rule factories by default:

RuleDescription
noop()Returns the input Tree as is.
chain(rules: Rule[])Returns a Rule that's the concatenation of other rules.
forEach(op: FileOperator)Returns a Rule that applies an operator to every file of the input Tree.
move(root: string)Moves all the files from the input to a subdirectory.
merge(other: Tree)Merge the input tree with the other Tree.
contentTemplate<T>(options: T)Apply a content template (see the Template section) to the entire Tree.
pathTemplate<T>(options: T)Apply a path template (see the Template section) to the entire Tree.
template<T>(options: T)Apply both path and content templates (see the Template section) to the entire Tree.
filter(predicate: FilePredicate<boolean>)Returns the input Tree with files that do not pass the FilePredicate.
`branch

Examples

Simple

An example of a simple Schematics which creates a "hello world" file, using an option to determine its path:

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

export default function MySchematic(options: any) {
  return (tree: Tree) => {
    tree.create(options.path + '/hi', 'Hello world!');
    return tree;
  };
}

A few things from this example:

  1. The function receives the list of options from the tooling.
  2. It returns a Rule, which is a transformation from a Tree to another Tree.

Future Work

Schematics is not done yet. Here's a list of things we are considering:

  • Smart defaults for Options. Having a JavaScript function for default values based on other default values.
  • Prompt for input options. This should only be prompted for the original schematics, dependencies to other schematics should not trigger another prompting.
  • Tasks for running tooling-specific jobs before and after a schematics has been scaffolded. Such tasks can involve initialize git, or npm install. A specific list of tasks should be provided by the tool, with unsupported tasks generating an error.

Keywords

FAQs

Last updated on 18 Jan 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc