您好,欢迎访问一九零五行业门户网

什么是Angular Schematics?如何搭建?(详解)

什么是angular schematics?如何在本地开发你的 angular schematics?下面本篇文章就来给大家详细介绍一下,并通过一个例子来更好的熟悉,希望对大家有所帮助!
什么是angular schematics?angular schematics 是基于模板(template-based)的,angular 特有的代码生成器,当然它不仅仅是生成代码,也可以修改我们的代码,它使得我们可以基于 angular cli 去实现我们自己的一些自动化操作。【相关教程推荐:《angular教程》】
相信在平时开发 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: 主要与项目打包编译相关,在这不做具体介绍
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 install。rule:为我们制定的操作逻辑。
实现一个 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": "http://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": []}
在以上的定义中,我们的命令将会接收两个参数分别为 defaultlanguage,i18n,我们以 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 代表该参数的类型是 string。default 为该参数的默认值为 zh-cn。x-prompt 定义与用户的交互,message 为我们对用户进行的相关提问,在这里我们的 type 为 list 代表我们会为用户提供 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)]); };}
下面时使用到的函数的具体实现:
// getworkspacefunction 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
// addsourcefilesfunction addsourcefiles(options: addoptions): rule { return chain([ mergewith( apply(url('./files'), [ applytemplates({ defaultlanguage: options.defaultlanguage }), move(`${projectworkspace.sourceroot}/app`) ]) ) ]);}
// readjsonfunction 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; }}// writejsonexport function writejson(tree: tree, file: string, source: any): void { tree.overwrite(file, json.stringify(source, null, 2));}// readpackagejsonfunction readpackagejson(tree: tree, type?: string): any { return readjson(tree, package_json_path, type);}// writepackagejsonfunction writepackagejson(tree: tree, json: any): any { return writejson(tree, package_json_path, json);}// addpackagefunction 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?如何搭建?(详解)的详细内容。
其它类似信息

推荐信息