详解创建自定义的Angular Schematics

本文对 Angular Schematics 进行了介绍,并创建了一个用于创建自定义 Component 的 Schematics ,然后在 Angular 项目中以它为模板演练了通过 Schematics 添加自定义的 Component 。

1. 什么是 Schematics?

简单来说,Schematics 是一个项目处理工具,可以帮助我们对 Angular 项目中的内容进行成批的处理。

比如我们在是使用 Angular CLI 的时候,可能使用过诸如 ng g c myComponent 之类的命令来帮助我们创建一个新 Component ,这个命令将各种工作成批完成,添加 Component 代码文件、模板文件、样式文件、添加到 Module 中等等。

现在,我们也可以自己来创建自定义的 Schematics 。在下面的介绍中,我们将创建一个自定义的 Schematics,实现这个类似的功能,我们还提供了命令选项的支持。

对于 Schematics 的介绍,请参考:Schematics — An Introduction

2. 演练创建 Schematics

首先您需要安装  Schematics 的命令行工具。

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

然后,就可以使用这个工具来创建您的第一个 Schematics 了,我们将它命名为 my-first-schema。

schematics blank --name=my-first-schema

这会创建名为 my-frist-schema 的文件夹,在其中已经创建了多个文件,如下所示。

我们使用 blank 为我们后继的工作打好基础。

然后,我们定义自己的 Schematics 。

需要将 src 文件夹中的 collection.json 修改成如下内容:

{
 "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
 "schematics": {
 "my-first-schema": {
  "aliases": ["mfs"],
  "factory": "./my-first-schema",
  "description": "my first schematic.",
  "schema": "./my-first-schema/schema.json"
 }
 }
}

$schema => 定义该 collection 架构的 url 地址.

schematics => 这是你的  schematics 定义.

my-first-schema => 以后使用这个  schematics 的 cli 名称.

aliases => 别名.

factory => 定义代码.

Description => 简单的说明.

Schema => 你的 schema 的设置. 这个文件的内容应该如下所示。我们在其中定义了多个自定义的选项,在使用这个 Schematics 的时候,可以通过这些选项来设置生成的内容。

{
 "$schema": "http://json-schema.org/schema",
 "id": "my-first-schema",
 "title": "my1er Schema",
 "type": "object",
 "properties": {
  "name": {
  "type": "string",
  "default": "name"
  },
  "path": {
  "type": "string",
  "default": "app"
  },
  "appRoot": {
  "type": "string"
  },
  "sourceDir": {
  "type": "string",
  "default": "src/app"
  },
  "service": {
  "type": "boolean",
  "default": false,
  "description": "Flag to indicate whether service should be generated.",
  "alias": "vgs"
  }
 }
}

这里可以设置你的 schematics 的命令选项,类似于在使用 g 来创建一个新的组件的时候,您可以使用一个 --change-detection 的选项。

ng g c component-name --change-detection

您还需要为您的选项创建一个接口 schema.ts。

export interface schemaOptions {
 name: string;
 appRoot: string;
 path: string;
 sourceDir: string;
 service: boolean;
}

下面才是我们的核心内容 index.ts 。这里定义我们 schematics 的逻辑实现。

import { chain, mergeWith } from '@angular-devkit/schematics';
import { apply, filter, move, Rule, template, url, branchAndMerge } from '@angular-devkit/schematics';
import { normalize } from '@angular-devkit/core';
import { dasherize, classify} from "@angular-devkit/core/src/utils/strings";
import { schemaOptions } from './schema';

const stringUtils = {dasherize, classify};

function filterTemplates(options: schemaOptions): Rule {
 if (!options.service) {
 return filter(path => !path.match(/\.service\.ts$/) && !path.match(/-item\.ts$/) && !path.match(/\.bak$/));
 }
 return filter(path => !path.match(/\.bak$/));
}

export default function (options: schemaOptions): Rule {
 // TODO: Validate options and throw SchematicsException if validation fails
 options.path = options.path ? normalize(options.path) : options.path;

 const templateSource = apply(url('./files'), [
  filterTemplates(options),
  template({
   ...stringUtils,
   ...options
  }),
  move('src/app/my-schema')
  ]);

  return chain([
  branchAndMerge(chain([
   mergeWith(templateSource)
  ])),
  ]);

}

Classify is for a little magic in the templates for the schematics.

filterTemplates is a filter for use or add more files.

option.path it's very important you use this option for create the folders and files in the angular app.

templateSource use the cli options and “build” the files into “./files” for create you final template (with the cli options changes)

在 my-first-schema 文件夹中,创建名为 files 的文件夹,添加三个文件:

my-first-schema.component.ts

import { Component, Input, } from '@angular/core';

@Component({
 selector: 'my-first-schema-component',
 templateUrl: './my-first-schema.component.html',
 styleUrls: [ './my-first-schema.component.css' ]
})

export class MyFirstSchemaComponent {

 constructor(){
 console.log( '<%= classify(name) %>' );
 }

}

这是一个模板文件,其中可以看到 <%= classify(name) %> 的内容。当你在使用这个 schematics 的时候,classify 将用来获取 options 中的 name 的值。

my-first-schema.component.html

<% if (service) { %>
 <h1>Hola Service</h1>
<% } %>

<% if (!service) { %>
 <h1>Hola no Service</h1>
<% } %>

这里的 service 同样来自 options,我们定义了一个 Boolean 类型的选项。

my-first-schema.component.css,这个文件目前保持为空即可。

回到控制台,在你的项目文件夹中执行 build 命令:npm run build

定义已经完成。

3. 在 Angular 项目中使用这个 Schematics

下面,我们在其它文件夹中,创建一个新的 Angular 项目,以便使用刚刚创建的这个 Schematics。

ng new test-schematics

进入到这个项目中,使用我们新创建的 schematics。

在其 node-modules 文件夹中创建名为 mfs 的模块文件夹,我们还没有将新创建的 Schematics 上传到 Npm 中,这里我们手工将其复制到新建的 Angular 项目中。

将您前面创建的 schematics 项目中所有的文件(除了 node_modules 文件夹和 package-lock.json 文件之外),复制到这个 mfs 文件夹中,以便使用。

现在,我们可以使用前面创建的这个 schematics 了。

ng g my-first-schema mfs  — service  — name=”Mfs”  — collection mfs

这里设置了 name 和 service 的值。

你应该看到如下的输出:

PS test-schematics> ng g my-first-schema mfs --service --name="Mfs" --collection mfs
  create src/app/my-schema/my-first-schema.component.css (0 bytes)
  create src/app/my-schema/my-first-schema.component.html (33 bytes)
  create src/app/my-schema/my-first-schema.component.ts (320 bytes)
PS test-schematics>

在刚才新建的 Angular 项目 src/app 文件夹中,已经新建了一个名为 my-first-schema 的文件夹,其中包含了三个文件。

打开 my-first-schema.component.ts 文件,可以看到替换之后的内容

import { Component, Input, } from '@angular/core';

@Component({
 selector: 'my-first-schema-component',
 templateUrl: './my-first-schema.component.html',
 styleUrls: [ './my-first-schema.component.css' ]
})

export class MyFirstSchemaComponent {

 constructor(){
 console.log( 'Mfs' );
 }

}

而在 my-first-schema.component.html 中,可以看到 --service 的影响。

<h1>Hola Service</h1>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 详解创建自定义的Angular Schematics

    本文对 Angular Schematics 进行了介绍,并创建了一个用于创建自定义 Component 的 Schematics ,然后在 Angular 项目中以它为模板演练了通过 Schematics 添加自定义的 Component . 1. 什么是 Schematics? 简单来说,Schematics 是一个项目处理工具,可以帮助我们对 Angular 项目中的内容进行成批的处理. 比如我们在是使用 Angular CLI 的时候,可能使用过诸如 ng g c myComponent

  • 详解Vue自定义指令及使用

    一.什么是指令 学习 vue 的时候肯定会接触指令,那么什么是指令呢? 在 vue 中提供了一些对于页面和数据更为方便的输出,这些操作就叫做指令,以 v-xxx 表示,比如 html 页面中的属性 <div v-xxx ></div> 比如在 angular 中 以 ng-xxx 开头的就叫做指令 指令中封装了一些 DOM 行为,结合属性作为一个暗号,暗号有对应的值,根据不同的值,会进行相关 DOM 操作的绑定,即可以进行一些模板的操作 vue 中常用的一些内置 v- 指令 v-t

  • 详解java自定义类

    引用数据类型(类) 引用数据类型分类 提到引用数据类型(类),其实我们对它并不陌生,之前使用过的Scanner类.Random类. 我们可以把类的类型为两种: 第一种,Java为我们提供好的类,如Scanner类,Random类等,这些已存在的类中包含了很多的方法与属性,可供我们使用. 第二种,我们自己创建的类,按照类的定义标准,可以在类中包含多个方法与属性,来供我们使用. 这里我们主要介绍第二种情况的简单使用. 自定义数据类型概述 我们在Java中,将现实生活中的事物抽象成了代码.这时,我们可

  • SpringBoot详解实现自定义异常处理页面方法

    目录 1.相关介绍 2.代码实现 3.运行测试 1.相关介绍 当发生异常时, 跳转到我们自定义的异常处理页面. SpringBoot中只需在静态资源目录下创建一个error文件夹, 并把异常处理页面放入其中, 页面的命名与异常错误代码对应, 如404.html, 500.html. 5xx.html可以对应所有错误代码为5开头的错误 默认静态资源目录为类路径(resources)下的: /static /public /resources /META-INF/resources 2.代码实现 H

  • TabLayout用法详解及自定义样式

    TabLayout的默认样式: app:theme="@style/Widget.Design.TabLayout" 从系统定义的该样式继续深入: <style name="Widget.Design.TabLayout" parent="Base.Widget.Design.TabLayout"> <item name="tabGravity">fill</item> <item n

  • 详解JavaScript自定义函数

    一.定义方法:在Javascript中必须用function关键字 function funcName(arg1,arg2...) { statements; return "变量值"; //返回值可以根据函数的需要 } 函数名是函数自身的一个引用.此种方式创立的函数引用是独立存在的,无法删除. 1.调用函数:函数名(参数列表). 传递的参数不必与函数定义的参数个数一致,并且可以设定函数参数的默认值. function example(a,b){ var a = arguments[0

  • 详解Django自定义图片和文件上传路径(upload_to)的2种方式

    最近在做一个仿知乎网站的项目了,里面涉及很多图片和文件上传.趁此机会我给大家总结下Django自定义图片和文件上传路径的2种方式吧. 方法1: 在Django模型中定义upload_to选项. Django模型中的ImageField和FileField的upload_to选项是必填项,其存储路径是相对于MEIDA_ROOT而来的. 我们来看一个简单案例(如下所示).如果你的MEDIA_ROOT是/media/文件夹,而你的上传文件夹upload_to="avatar", 那么你上传的

  • 详解MindSpore自定义模型损失函数

    目录 一.技术背景 二.MindSpore内置的损失函数 三.自定义损失函数 四.自定义其他算子 五.多层算子的应用 六.重定义reduction 一.技术背景 损失函数是机器学习中直接决定训练结果好坏的一个模块,该函数用于定义计算出来的结果或者是神经网络给出的推测结论与正确结果的偏差程度,偏差的越多,就表明对应的参数越差.而损失函数的另一个重要性在于会影响到优化函数的收敛性,如果损失函数的指数定义的太高,稍有参数波动就导致结果的巨大波动的话,那么训练和优化就很难收敛.一般我们常用的损失函数是M

  • 详解Vue 自定义hook 函数

    目录 定义 使用 封装发ajax请求的hook函数(ts版本) 定义 什么是hook? 本质是一个函数,把 setup 函数中使用的 Composition API (组合API)进行了封装 类似于 vue2.x 中的 mixin 自定义 hook 的优势: 复用代码,让 setup 中的逻辑更清楚易懂 使用 首先我们做一个功能,鼠标点击屏幕,获取坐标: <template> <h2>当前鼠标的坐标是:x:{{ point.x }},y:{{ point.y }}</h2&g

  • Spring Boot详解创建和运行基础流程

    目录 1. 初始 Spring Boot 1.1 什么是Spring Boot 1.2 Spring Boot 的优点 2. 创建 Spring Boot 项目(Idea) 2.1 首先安装 Spring Assistant 插件 2.2 重启Idea-New Project ① 点击 Spring Assistant 直接Next就可以了 ② Next 之后的页面介绍 ③ 引入依赖, 选择Spring Boot的版本 ④ 选择项目名称和保存路径 ⑤ Spring Boot 项目创建完成 3.

随机推荐