Angular Schematics如何应用于具体项目搭建?

2026-04-03 07:451阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计3198个文字,预计阅读时间需要13分钟。

Angular Schematics如何应用于具体项目搭建?

Angular Schematics 是 Angular CLI 的一个强大功能,它允许开发者通过预定义的模板来快速生成代码。下面是对其的简单介绍和如何在本地开发你的 Angular Schematics 的步骤。

什么是 Angular Schematics?

Angular Schematics 是一种声明式工具,它允许你定义如何将一组文件和目录转换为目标代码。Schematics 可以用来创建组件、服务、指令等,甚至可以用来迁移现有代码。

如何在本地开发你的 Angular Schematics?

1. 安装 Node.js 和 npm:确保你的系统上安装了 Node.js 和 npm,因为 Schematics 是基于 Node.js 的。

2. 安装 Angular CLI:通过 npm 安装 Angular CLI:

bash npm install -g @angular/cli

3. 创建一个新的 Schematics 项目:

bash ng new my-schematics cd my-schematics

4. 安装 Schematics 工具:

bash ng generate @angular/schematics:schematic my-schematic

5. 编辑 Schematics:在 `e2e` 文件夹中,找到 `my-schematic` 文件夹,然后编辑 `schema.json` 和 `files.js` 文件来定义你的 Schematics。

6. 测试 Schematics:在 `e2e` 文件夹中运行以下命令来测试你的 Schematics:

bash ng e2e

示例

假设你想要创建一个简单的 Schematics,用于生成一个带有特定名称的组件。

1. 创建 Schematics 项目:

bash ng new my-schematics cd my-schematics

2. 安装 Schematics 工具:

bash ng generate @angular/schematics:schematic my-component

3. 编辑 Schematics:

- `schema.json`:

json { $schema: https://raw.githubusercontent.com/angular/angular-cli/master/packages/schematics-.json, name: my-component, description: A Schematics that generates a component with a specific name., type: component, templates: { src/app/components/my-component/my-component.component.: Component HTML content, src/app/components/my-component/my-component.component.ts: Component TypeScript content } }

- `files.js`:

typescript import { SchematicsException, Tree } from '@angular-devkit/schematics'; import { Schema as MyComponentSchema } from './schema';

function myComponent(_host: Tree, options: MyComponentSchema) { if (!options.name) { throw new SchematicsException('Name is required'); }

const templateContent=`${options.name}`; const componentContent=`import { Component } from '@angular/core';

@Component({ selector: 'app-${options.name}', templateUrl: './${options.name}.component.', styleUrls: ['./${options.name}.component.css'] }) export class ${options.name}Component { constructor() {}

name='${options.name}'; }`;

_host.create( `src/app/components/${options.name}/${options.name}.component.`, templateContent ); _host.create( `src/app/components/${options.name}/${options.name}.component.ts`, componentContent );

return _host; }

export function default_1() { return myComponent; }

4. 测试 Schematics:

bash ng e2e

这样,你就创建了一个简单的 Angular Schematics,它可以生成一个带有特定名称的组件。希望这个例子能帮助你更好地理解 Angular Schematics!

什么是Angular Schematics?如何在本地开发你的 Angular Schematics?下面本篇文章就来给大家详细介绍一下,并通过一个例子来更好的熟悉,希望对大家有所帮助!

什么是Angular Schematics?

Angular Schematics 是基于模板(Template-based)的,Angular 特有的代码生成器,当然它不仅仅是生成代码,也可以修改我们的代码,它使得我们可以基于 Angular CLI 去实现我们自己的一些自动化操作。

相信在平时开发 Angular 项目的同时,大家都用过 ng generate component component-name, ng add @angular/materials, ng generate module module-name,这些都是 Angular 中已经为我们实现的一些 CLI,那么我们应该如何在自己的项目中去实现基于自己项目的 CLI 呢?本文将会基于我们在 ng-devui-admin 中的实践来进行介绍。欢迎大家持续的关注,后续我们将会推出更加丰富的 CLI 帮助大家更快搭建一个 Admin 页面。

如何在本地开发你的 Angular Schematics

在本地开发你需要先安装 schematics 脚手架

npm install -g @angular-devkit/schematics-cli # 安装完成之后新建一个schematics项目 schematics blank --name=your-schematics

新建项目之后你会看到如下目录结构,代表你已经成功创建一个 shematics 项目。

重要文件介绍

  • tsconfig.json: 主要与项目打包编译相关,在这不做具体介绍

    Angular Schematics如何应用于具体项目搭建?

  • collection.json:与你的 CLI 命令相关,用于定义你的相关命令

{ "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { "first-schematics": { "description": "A blank schematic.", "factory": "./first-schematics/index#firstSchematics" } } }

first-schematics: 命令的名字,可以在项目中通过 ng g first-schematics:first-schematics 来运行该命令。description: 对该条命令的描述。factory: 命令执行的入口函数 通常还会有另外一个属性 schema,我们将在后面进行讲解。

  • index.ts:在该文件中实现你命令的相关逻辑

import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; export function firstSchematics(_options: any): Rule { return (tree: Tree, _context: SchematicContext) => { return tree; }; }

在这里我们先看几个需要了解的参数:tree:在这里你可以将 tree 理解为我们整个的 angular 项目,你可以通过 tree 新增文件,修改文件,以及删除文件。_context:该参数为 schematics 运行的上下文,比如你可以通过 context 执行 npm installRule:为我们制定的操作逻辑。

实现一个 ng-add 指令

现在我们通过实现一个 ng-add 指令来更好的熟悉。

同样是基于以上我们已经创建好的项目。

新建命令相关的文件

首先我们在 src 目录下新建一个目录 ng-add,然后在该目录下添加三个文件 index.ts, schema.json, schema.ts,之后你的目录结构应该如下:

配置 collection.json

之后我们在 collection.json 中配置该条命令:

{ "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { ..., "ng-add": { "factory": "./ng-add/index", "description": "Some description about your schematics", "schema": "./ng-add/schema.json" } } }

files 目录中加入我们想要插入的文件

关于 template 的语法可以参考 ejs 语法

app.component.html.template

<div class="my-app"> <% if (defaultLanguage === 'zh-cn') { %>你好,Angular Schematics!<% } else { %>Hello, My First Angular Schematics!<% } %> <h1>{{ title }}</h1> </div>

app.component.scss.template

.app { display: flex; justify-content: center; align-item: center; }

app.component.ts.template

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = <% if (defaultLanguage === 'zh-cn') { %>'你好'<% } else { %>'Hello'<% } %>; }

开始实现命令逻辑

  • schema.json:在该文件中定义与用户的交互

{ "$schema": "json-schema.org/schema", "id": "SchematicsDevUI", "title": "DevUI Options Schema", "type": "object", "properties": { "defaultLanguage": { "type": "string", "description": "Choose the default language", "default": "zh-cn", "x-prompt": { "message": "Please choose the default language you want to use: ", "type": "list", "items": [ { "value": "zh-cn", "label": "简体中文 (zh-ch)" }, { "value": "en-us", "label": "English (en-us)" } ] } }, "i18n": { "type": "boolean", "default": true, "description": "Config i18n for the project", "x-prompt": "Would you like to add i18n? (default: Y)" } }, "required": [] }

在以上的定义中,我们的命令将会接收两个参数分别为 defaultLanguagei18n,我们以 defaultLanguage 为例讲解对参数的相关配置:

{ "defaultLanguage": { "type": "string", "description": "Choose the default language", "default": "zh-cn", "x-prompt": { "message": "Please choose the default language you want to use: ", "type": "list", "items": [ { "value": "zh-cn", "label": "简体中文 (zh-ch)" }, { "value": "en-us", "label": "English (en-us)" } ] } } }

type 代表该参数的类型是 stringdefault 为该参数的默认值为 zh-cnx-prompt 定义与用户的交互,message 为我们对用户进行的相关提问,在这里我们的 typelist 代表我们会为用户提供 items 中列出的选项供用户进行选择。

  • schema.ts:在该文件中定义我们接收到的参数类型

export interface Schema { defaultLanguage: string; i18n: boolean; }

  • index.ts:在该文件中实现我们的操作逻辑,假设在此次 ng-add 操作中,我们根据用户输入的 defaultLanguage, i18n 来对用户的项目进行相应的更改,并且插入相关的 npm 包,再进行安装。

import { apply, applyTemplates, chain, mergeWith, move, Rule, SchematicContext, SchematicsException, Tree, url } from '@angular-devkit/schematics'; import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'; import { Schema as AddOptions } from './schema'; let projectWorkspace: { root: string; sourceRoot: string; defaultProject: string; }; export type packgeType = 'dependencies' | 'devDependencies' | 'scripts'; export const PACKAGES_I18N = [ '@devui-design/icons@^1.2.0', '@ngx-translate/core@^13.0.0', '@ngx-translate/http-loader@^6.0.0', 'ng-devui@^11.1.0' ]; export const PACKAGES = ['@devui-design/icons@^1.2.0', 'ng-devui@^11.1.0']; export const PACKAGE_JSON_PATH = 'package.json'; export const ANGULAR_JSON_PATH = 'angular.json'; export default function (options: AddOptions): Rule { return (tree: Tree, context: SchematicContext) => { // 获取项目空间中我们需要的相关变量 getWorkSpace(tree); // 根据是否选择i18n插入不同的packages const packages = options.i18n ? PACKAGES_I18N : PACKAGES; addPackage(tree, packages, 'dependencies'); // 执行 npm install context.addTask(new NodePackageInstallTask()); // 自定义的一系列 Rules return chain([removeOriginalFiles(), addSourceFiles(options)]); }; }

下面时使用到的函数的具体实现:

// getWorkSpace function getWorkSpace(tree: Tree) { let angularJSON; let buffer = tree.read(ANGULAR_JSON_PATH); if (buffer) { angularJSON = JSON.parse(buffer.toString()); } else { throw new SchematicsException( 'Please make sure the project is an Angular project.' ); } let defaultProject = angularJSON.defaultProject; projectWorkspace = { root: '/', sourceRoot: angularJSON.projects[defaultProject].sourceRoot, defaultProject }; return projectWorkspace; }

// removeOriginalFiles // 根据自己的需要选择需要删除的文件 function removeOriginalFiles() { return (tree: Tree) => { [ `${projectWorkspace.sourceRoot}/app/app.component.ts`, `${projectWorkspace.sourceRoot}/app/app.component.html`, `${projectWorkspace.sourceRoot}/app/app.component.scss`, `${projectWorkspace.sourceRoot}/app/app.component.css` ] .filter((f) => tree.exists(f)) .forEach((f) => tree.delete(f)); }; }

将 files 下的文件拷贝到指定的路径下,关于 chain, mergeWith, apply, template 的详细使用方法可以参考 Schematics

// addSourceFiles function addSourceFiles(options: AddOptions): Rule { return chain([ mergeWith( apply(url('./files'), [ applyTemplates({ defaultLanguage: options.defaultLanguage }), move(`${projectWorkspace.sourceRoot}/app`) ]) ) ]); }

// readJson function readJson(tree: Tree, file: string, type?: string): any { if (!tree.exists(file)) { return null; } const sourceFile = tree.read(file)!.toString('utf-8'); try { const json = JSON.parse(sourceFile); if (type && !json[type]) { json[type] = {}; } return json; } catch (error) { console.log(`Failed when parsing file ${file}.`); throw error; } } // writeJson export function writeJson(tree: Tree, file: string, source: any): void { tree.overwrite(file, JSON.stringify(source, null, 2)); } // readPackageJson function readPackageJson(tree: Tree, type?: string): any { return readJson(tree, PACKAGE_JSON_PATH, type); } // writePackageJson function writePackageJson(tree: Tree, json: any): any { return writeJson(tree, PACKAGE_JSON_PATH, json); } // addPackage function addPackage( tree: Tree, packages: string | string[], type: packgeType = 'dependencies' ): Tree { const packageJson = readPackageJson(tree, type); if (packageJson == null) { return tree; } if (!Array.isArray(packages)) { packages = [packages]; } packages.forEach((pck) => { const splitPosition = pck.lastIndexOf('@'); packageJson[type][pck.substr(0, splitPosition)] = pck.substr( splitPosition + 1 ); }); writePackageJson(tree, packageJson); return tree; }

为了保持 index.ts 文件的简洁,可以将相关操作的方法抽取到一个新的文件中进行引用。

测试 ng-add

至此我们已经完成了 ng-add 命令,现在我们对该命令进行测试:

  • ng new test 初始化一个 Angular 项目
  • cd test && mkdir libs 在项目中添加一个 libs 文件夹,将图中标蓝的文件拷贝到其中

  • 之后在命令行中执行 npm link libs/
  • link 完成之后 cd libs && npm run build && cd ..
  • 现在执行 ng add first-schematics 之后会看到如下提示

  • 最后我们通过 npm start 来查看执行的结果如下

结语

综上简单介绍了一个 Schematics 的实现,更多的一些应用欢迎大家查看 ng-devui-admin 中的实现。

更多编程相关知识,请访问:编程学习!!

以上就是什么是Angular Schematics?如何搭建?(详解)的详细内容,更多请关注自由互联其它相关文章!

本文共计3198个文字,预计阅读时间需要13分钟。

Angular Schematics如何应用于具体项目搭建?

Angular Schematics 是 Angular CLI 的一个强大功能,它允许开发者通过预定义的模板来快速生成代码。下面是对其的简单介绍和如何在本地开发你的 Angular Schematics 的步骤。

什么是 Angular Schematics?

Angular Schematics 是一种声明式工具,它允许你定义如何将一组文件和目录转换为目标代码。Schematics 可以用来创建组件、服务、指令等,甚至可以用来迁移现有代码。

如何在本地开发你的 Angular Schematics?

1. 安装 Node.js 和 npm:确保你的系统上安装了 Node.js 和 npm,因为 Schematics 是基于 Node.js 的。

2. 安装 Angular CLI:通过 npm 安装 Angular CLI:

bash npm install -g @angular/cli

3. 创建一个新的 Schematics 项目:

bash ng new my-schematics cd my-schematics

4. 安装 Schematics 工具:

bash ng generate @angular/schematics:schematic my-schematic

5. 编辑 Schematics:在 `e2e` 文件夹中,找到 `my-schematic` 文件夹,然后编辑 `schema.json` 和 `files.js` 文件来定义你的 Schematics。

6. 测试 Schematics:在 `e2e` 文件夹中运行以下命令来测试你的 Schematics:

bash ng e2e

示例

假设你想要创建一个简单的 Schematics,用于生成一个带有特定名称的组件。

1. 创建 Schematics 项目:

bash ng new my-schematics cd my-schematics

2. 安装 Schematics 工具:

bash ng generate @angular/schematics:schematic my-component

3. 编辑 Schematics:

- `schema.json`:

json { $schema: https://raw.githubusercontent.com/angular/angular-cli/master/packages/schematics-.json, name: my-component, description: A Schematics that generates a component with a specific name., type: component, templates: { src/app/components/my-component/my-component.component.: Component HTML content, src/app/components/my-component/my-component.component.ts: Component TypeScript content } }

- `files.js`:

typescript import { SchematicsException, Tree } from '@angular-devkit/schematics'; import { Schema as MyComponentSchema } from './schema';

function myComponent(_host: Tree, options: MyComponentSchema) { if (!options.name) { throw new SchematicsException('Name is required'); }

const templateContent=`${options.name}`; const componentContent=`import { Component } from '@angular/core';

@Component({ selector: 'app-${options.name}', templateUrl: './${options.name}.component.', styleUrls: ['./${options.name}.component.css'] }) export class ${options.name}Component { constructor() {}

name='${options.name}'; }`;

_host.create( `src/app/components/${options.name}/${options.name}.component.`, templateContent ); _host.create( `src/app/components/${options.name}/${options.name}.component.ts`, componentContent );

return _host; }

export function default_1() { return myComponent; }

4. 测试 Schematics:

bash ng e2e

这样,你就创建了一个简单的 Angular Schematics,它可以生成一个带有特定名称的组件。希望这个例子能帮助你更好地理解 Angular Schematics!

什么是Angular Schematics?如何在本地开发你的 Angular Schematics?下面本篇文章就来给大家详细介绍一下,并通过一个例子来更好的熟悉,希望对大家有所帮助!

什么是Angular Schematics?

Angular Schematics 是基于模板(Template-based)的,Angular 特有的代码生成器,当然它不仅仅是生成代码,也可以修改我们的代码,它使得我们可以基于 Angular CLI 去实现我们自己的一些自动化操作。

相信在平时开发 Angular 项目的同时,大家都用过 ng generate component component-name, ng add @angular/materials, ng generate module module-name,这些都是 Angular 中已经为我们实现的一些 CLI,那么我们应该如何在自己的项目中去实现基于自己项目的 CLI 呢?本文将会基于我们在 ng-devui-admin 中的实践来进行介绍。欢迎大家持续的关注,后续我们将会推出更加丰富的 CLI 帮助大家更快搭建一个 Admin 页面。

如何在本地开发你的 Angular Schematics

在本地开发你需要先安装 schematics 脚手架

npm install -g @angular-devkit/schematics-cli # 安装完成之后新建一个schematics项目 schematics blank --name=your-schematics

新建项目之后你会看到如下目录结构,代表你已经成功创建一个 shematics 项目。

重要文件介绍

  • tsconfig.json: 主要与项目打包编译相关,在这不做具体介绍

    Angular Schematics如何应用于具体项目搭建?

  • collection.json:与你的 CLI 命令相关,用于定义你的相关命令

{ "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { "first-schematics": { "description": "A blank schematic.", "factory": "./first-schematics/index#firstSchematics" } } }

first-schematics: 命令的名字,可以在项目中通过 ng g first-schematics:first-schematics 来运行该命令。description: 对该条命令的描述。factory: 命令执行的入口函数 通常还会有另外一个属性 schema,我们将在后面进行讲解。

  • index.ts:在该文件中实现你命令的相关逻辑

import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; export function firstSchematics(_options: any): Rule { return (tree: Tree, _context: SchematicContext) => { return tree; }; }

在这里我们先看几个需要了解的参数:tree:在这里你可以将 tree 理解为我们整个的 angular 项目,你可以通过 tree 新增文件,修改文件,以及删除文件。_context:该参数为 schematics 运行的上下文,比如你可以通过 context 执行 npm installRule:为我们制定的操作逻辑。

实现一个 ng-add 指令

现在我们通过实现一个 ng-add 指令来更好的熟悉。

同样是基于以上我们已经创建好的项目。

新建命令相关的文件

首先我们在 src 目录下新建一个目录 ng-add,然后在该目录下添加三个文件 index.ts, schema.json, schema.ts,之后你的目录结构应该如下:

配置 collection.json

之后我们在 collection.json 中配置该条命令:

{ "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { ..., "ng-add": { "factory": "./ng-add/index", "description": "Some description about your schematics", "schema": "./ng-add/schema.json" } } }

files 目录中加入我们想要插入的文件

关于 template 的语法可以参考 ejs 语法

app.component.html.template

<div class="my-app"> <% if (defaultLanguage === 'zh-cn') { %>你好,Angular Schematics!<% } else { %>Hello, My First Angular Schematics!<% } %> <h1>{{ title }}</h1> </div>

app.component.scss.template

.app { display: flex; justify-content: center; align-item: center; }

app.component.ts.template

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = <% if (defaultLanguage === 'zh-cn') { %>'你好'<% } else { %>'Hello'<% } %>; }

开始实现命令逻辑

  • schema.json:在该文件中定义与用户的交互

{ "$schema": "json-schema.org/schema", "id": "SchematicsDevUI", "title": "DevUI Options Schema", "type": "object", "properties": { "defaultLanguage": { "type": "string", "description": "Choose the default language", "default": "zh-cn", "x-prompt": { "message": "Please choose the default language you want to use: ", "type": "list", "items": [ { "value": "zh-cn", "label": "简体中文 (zh-ch)" }, { "value": "en-us", "label": "English (en-us)" } ] } }, "i18n": { "type": "boolean", "default": true, "description": "Config i18n for the project", "x-prompt": "Would you like to add i18n? (default: Y)" } }, "required": [] }

在以上的定义中,我们的命令将会接收两个参数分别为 defaultLanguagei18n,我们以 defaultLanguage 为例讲解对参数的相关配置:

{ "defaultLanguage": { "type": "string", "description": "Choose the default language", "default": "zh-cn", "x-prompt": { "message": "Please choose the default language you want to use: ", "type": "list", "items": [ { "value": "zh-cn", "label": "简体中文 (zh-ch)" }, { "value": "en-us", "label": "English (en-us)" } ] } } }

type 代表该参数的类型是 stringdefault 为该参数的默认值为 zh-cnx-prompt 定义与用户的交互,message 为我们对用户进行的相关提问,在这里我们的 typelist 代表我们会为用户提供 items 中列出的选项供用户进行选择。

  • schema.ts:在该文件中定义我们接收到的参数类型

export interface Schema { defaultLanguage: string; i18n: boolean; }

  • index.ts:在该文件中实现我们的操作逻辑,假设在此次 ng-add 操作中,我们根据用户输入的 defaultLanguage, i18n 来对用户的项目进行相应的更改,并且插入相关的 npm 包,再进行安装。

import { apply, applyTemplates, chain, mergeWith, move, Rule, SchematicContext, SchematicsException, Tree, url } from '@angular-devkit/schematics'; import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'; import { Schema as AddOptions } from './schema'; let projectWorkspace: { root: string; sourceRoot: string; defaultProject: string; }; export type packgeType = 'dependencies' | 'devDependencies' | 'scripts'; export const PACKAGES_I18N = [ '@devui-design/icons@^1.2.0', '@ngx-translate/core@^13.0.0', '@ngx-translate/http-loader@^6.0.0', 'ng-devui@^11.1.0' ]; export const PACKAGES = ['@devui-design/icons@^1.2.0', 'ng-devui@^11.1.0']; export const PACKAGE_JSON_PATH = 'package.json'; export const ANGULAR_JSON_PATH = 'angular.json'; export default function (options: AddOptions): Rule { return (tree: Tree, context: SchematicContext) => { // 获取项目空间中我们需要的相关变量 getWorkSpace(tree); // 根据是否选择i18n插入不同的packages const packages = options.i18n ? PACKAGES_I18N : PACKAGES; addPackage(tree, packages, 'dependencies'); // 执行 npm install context.addTask(new NodePackageInstallTask()); // 自定义的一系列 Rules return chain([removeOriginalFiles(), addSourceFiles(options)]); }; }

下面时使用到的函数的具体实现:

// getWorkSpace function getWorkSpace(tree: Tree) { let angularJSON; let buffer = tree.read(ANGULAR_JSON_PATH); if (buffer) { angularJSON = JSON.parse(buffer.toString()); } else { throw new SchematicsException( 'Please make sure the project is an Angular project.' ); } let defaultProject = angularJSON.defaultProject; projectWorkspace = { root: '/', sourceRoot: angularJSON.projects[defaultProject].sourceRoot, defaultProject }; return projectWorkspace; }

// removeOriginalFiles // 根据自己的需要选择需要删除的文件 function removeOriginalFiles() { return (tree: Tree) => { [ `${projectWorkspace.sourceRoot}/app/app.component.ts`, `${projectWorkspace.sourceRoot}/app/app.component.html`, `${projectWorkspace.sourceRoot}/app/app.component.scss`, `${projectWorkspace.sourceRoot}/app/app.component.css` ] .filter((f) => tree.exists(f)) .forEach((f) => tree.delete(f)); }; }

将 files 下的文件拷贝到指定的路径下,关于 chain, mergeWith, apply, template 的详细使用方法可以参考 Schematics

// addSourceFiles function addSourceFiles(options: AddOptions): Rule { return chain([ mergeWith( apply(url('./files'), [ applyTemplates({ defaultLanguage: options.defaultLanguage }), move(`${projectWorkspace.sourceRoot}/app`) ]) ) ]); }

// readJson function readJson(tree: Tree, file: string, type?: string): any { if (!tree.exists(file)) { return null; } const sourceFile = tree.read(file)!.toString('utf-8'); try { const json = JSON.parse(sourceFile); if (type && !json[type]) { json[type] = {}; } return json; } catch (error) { console.log(`Failed when parsing file ${file}.`); throw error; } } // writeJson export function writeJson(tree: Tree, file: string, source: any): void { tree.overwrite(file, JSON.stringify(source, null, 2)); } // readPackageJson function readPackageJson(tree: Tree, type?: string): any { return readJson(tree, PACKAGE_JSON_PATH, type); } // writePackageJson function writePackageJson(tree: Tree, json: any): any { return writeJson(tree, PACKAGE_JSON_PATH, json); } // addPackage function addPackage( tree: Tree, packages: string | string[], type: packgeType = 'dependencies' ): Tree { const packageJson = readPackageJson(tree, type); if (packageJson == null) { return tree; } if (!Array.isArray(packages)) { packages = [packages]; } packages.forEach((pck) => { const splitPosition = pck.lastIndexOf('@'); packageJson[type][pck.substr(0, splitPosition)] = pck.substr( splitPosition + 1 ); }); writePackageJson(tree, packageJson); return tree; }

为了保持 index.ts 文件的简洁,可以将相关操作的方法抽取到一个新的文件中进行引用。

测试 ng-add

至此我们已经完成了 ng-add 命令,现在我们对该命令进行测试:

  • ng new test 初始化一个 Angular 项目
  • cd test && mkdir libs 在项目中添加一个 libs 文件夹,将图中标蓝的文件拷贝到其中

  • 之后在命令行中执行 npm link libs/
  • link 完成之后 cd libs && npm run build && cd ..
  • 现在执行 ng add first-schematics 之后会看到如下提示

  • 最后我们通过 npm start 来查看执行的结果如下

结语

综上简单介绍了一个 Schematics 的实现,更多的一些应用欢迎大家查看 ng-devui-admin 中的实现。

更多编程相关知识,请访问:编程学习!!

以上就是什么是Angular Schematics?如何搭建?(详解)的详细内容,更多请关注自由互联其它相关文章!