在库中使用schematics——ng add与ng update
起步
创建一个angular库
ng new demo --create-application=false
ng g library my-lib
可见如下目录结构
├── node_modules/
├── projects
│ └── my-lib
│ ├── src
│ │ ├── lib
│ │ ├── public-api.ts
│ │ └── test.ts
│ ├── karma.conf.js
│ ├── ng-package.json
│ ├── package.json
│ ├── README.md
│ ├── tsconfig.lib.json
│ ├── tsconfig.lib.prod.json
│ ├── tsconfig.spec.json
│ └── tslint.json
├── README.md
├── package.json
├── .editorconfig
├── angular.json
├── tsconfig.base.json
├── tslint.json
└── tsconfig.json
添加projects/my-lib/schematics/collection.json文件
{
"$schema": "../../../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {
"ng-add": {
"description": "Add my library to the project.",
"factory": "./ng-add/index#ngAdd"
}
}
}
修改projects/my-lib/package.json文件
{
"name": "my-lib",
"version": "0.0.1",
"schematics": "./schematics/collection.json",
}
添加projects/my-lib/schematics/ng-add/index.ts文件
import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';
import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
import { strings } from '@angular-devkit/core';
// Just return the tree
export function ngAdd(options: any): Rule {
return (tree: Tree, context: SchematicContext) => {
context.addTask(new NodePackageInstallTask());
// 如果不是 Angular 项目则抛出错误
const workspaceConfig = tree.read('angular.json');
if (!workspaceConfig) {
throw new SchematicsException('Not an Angular CLI workspace');
}
const templateSource = apply(url('./files'), [
applyTemplates({
...strings
}),
move(normalize('')),
]);
return chain([mergeWith(templateSource)]);
};
}
添加projects/my-lib/schematics/ng-add/files 文件
└── files
└──index.ts
index.ts内容如下
// #docregion template
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class <%= classify(name) %>Service {
constructor(private http: HttpClient) { }
}
定义依赖类型,在projects/my-lib/package.json中添加
"ng-add": {
"save": "devDependencies"
}
修改projects/my-lib/tsconfig.schematics.json
{
"compilerOptions": {
"baseUrl": ".",
"lib": [
"es2018",
"dom"
],
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitThis": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"rootDir": "schematics",
"outDir": "../../dist/my-lib/schematics",
"skipDefaultLibCheck": true,
"skipLibCheck": true,
"sourceMap": true,
"strictNullChecks": true,
"target": "es6",
"types": [
"jasmine",
"node"
]
},
"include": [
"schematics/**/*"
],
"exclude": [
"schematics/*/files/**/*"
]
}
| 属性 | 说明 |
|---|---|
| rootDir | 指出在你的 schematics/ 文件夹中包含要编译的输入文件。 |
| outDir | 映射到了库的输出目录下。默认情况下,这是工作空间根目录下的 dist/my-lib 文件夹 |
修改projects/my-lib/package.json
{
"name": "my-lib",
"version": "0.0.1",
"scripts": {
"build": "../../node_modules/.bin/tsc -p tsconfig.schematics.json",
"copy:files": "cp --parents -p -r schematics/*/files/** ../../dist/my-lib/",
"copy:collection": "cp schematics/collection.json ../../dist/my-lib/schematics/collection.json",
"postbuild":"npm run copy:files && npm run copy:collection"
},
"peerDependencies": {
"@angular/common": "^7.2.0",
"@angular/core": "^7.2.0"
},
"schematics": "./schematics/collection.json",
"ng-add": {
"save": "devDependencies"
}
}
| 属性 | 说明 |
|---|---|
| build | 脚本使用自定义的 tsconfig.schematics.json 文件来编译你的原理图。 |
| copy | *语句将已编译的原理图文件复制到库的输出目录下的正确位置,以保持目录的结构。 |
| postbuild | 脚本会在 build 脚本完成后复制原理图文件。 |
修改根目录下的package.json,在scripts下加入
"build": "ng build my-lib --prod && cd ./projects/my-lib && npm run build",
"publish": "cd ./dist/my-lib && npm publish"
开始发布
npm publish
试一试ng add吧!
使用schematics修改项目
如何使用schematics修改项目中的package.json
|
方法 |
说明 |
|---|---|
| tree.overwrite() | 重新编排package.json |
| tree.read() | 读取文件内容 |
修改projects/my-lib/schematics/ng-add/index.ts
//读取angular.json的文件内容
const workspaceConfig = tree.read('angular.json');
// 如果不是 Angular 项目则抛出错误
if (!workspaceConfig) {
throw new SchematicsException('Not an Angular CLI workspace');
}
// 读取package.json的文件内容
const workspaceJson = tree.read('package.json');
let json=JSON.parse(workspaceJson)
json.script.hello="print('123')"
tree.overwrite('./package.json',JSON.stringify(json))
在node_modules添加引入与注入项
| 方法 | 说明 |
|---|---|
| addImportToModule(source: ts.SourceFile, modulePath: string, classifiedName: string, importPath: string): Change[] | 添加引入到module |
| ts.createSourFile | 创建资源文件 |
import * as ts from '@schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { addImportToModule } from '@schematics/angular/utility/ast-utils';
......
const modulePath = `/app.module.ts`;
const sourText = _tree.read(modulePath).toString('utf-8');
const sourceFile = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
const importPath = '@fortawesome/angular-fontawesome';
const moduleName = 'FontAwesomeModule'; //文件名为驼峰命名
const declarationChanges = addImportToModule(sourceFile, modulePath, moduleName, importPath);
const declarationRecorder = _tree.beginUpdate(modulePath);
for (const change of declarationChanges) {
if (change instanceof InsertChange) {
declarationRecorder.insertLeft(change.pos, change.toAdd);
}
}
_tree.commitUpdate(declarationRecorder);
更新文件
| 方法 | 说明 |
|---|---|
| tree.beginUpdate() | 更新内容 |
const htmlPath = `./app/src/app.component.html`;
const htmlStr = `\n\n`;
const modulePath = `/app.module.ts`;
const sourText = _tree.read(htmlPath).toString('utf-8');
const htmlSourceFile = ts.createSourceFile(htmlPath, sourceText, ts.ScriptTarget.Latest, true);
const htmlRecorder = _tree.beginUpdate(htmlPath);
htmlRecorder.insertLeft(htmlSourceFile.end, htmlStr);
_tree.commitUpdate(htmlRecorder);
package.json依赖项安装
| 方法 | 说明 |
|---|---|
| addPackageToPackageJson | 添加依赖支持 |
import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
......
const dependencies = [{ name: '@fortawesome/fontawesome-svg-core', version: '~1.2.25' }],
addPackageToPackageJson(
_tree,
dependency.name, //依赖包名
dependency.version,//版本
);
ng Update使用
在collection.json 同级目录,新建 migration.json 文件,并写入以下内容:
{
"$schema": "../../../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {
"migration002": {
"version": "0.0.2",
"description": "更新angular-schematics-tutorial到0.0.2版本时执行的更新",
"factory": "./ng-update/index#update"
}
}
}
在 package.json 中声明 ug-update 配置
在 package.json 中,添加以下项目:
"ng-update": {
"migrations": "./schematics/migration.json"
},
其作用,就是在执行 ng update 时,能够找到对应的配置文件
在projects/my-lib/schematics/ 目录下新建index.ts
import { Rule, Tree, SchematicContext, SchematicsException } from '@angular-devkit/schematics';
import { buildDefaultPath } from '@schematics/angular/utility/project';
import * as ts from 'typescript';
export function update(): Rule {
return (_tree: Tree, _context: SchematicContext) => {
// 解析angular项目
const workspaceConfigBuffer = _tree.read('angular.json');
if (!workspaceConfigBuffer) {
throw new SchematicsException('Not an Angular CLI workspace');
}
return tree.create('index.md','我更新了')
}
}
完结撒花!!
在库中使用schematics——ng add与ng update的更多相关文章
- Arduino下LCD1602综合探究(下)——如何减少1602的连线,LiquidCrystal库,LiquidCrystal库中bug的解决方法
一.前言: 上文中,笔者系统的阐述了1602的两种驱动方式,并简单的提到了Arduino的LiquidCrystal库.本文紧接上文,对以下两个问题进行更加深入的探讨:如何能够使1602对Arduin ...
- SharePoint 2013 文档库中PPT转换PDF
通过使用 PowerPoint Automation Services,可以从 PowerPoint 二进制文件格式 (.ppt) 和 PowerPoint Open XML 文件格式 (.pptx) ...
- 如何扫描出Android系统媒体库中视频文件
Android系统启动时会去扫描系统文件,并将系统支持的视频文件(mp4,3gp,wmv)扫描到媒体库(MediaStore)中,下面代码演示如何获得这些文件的信息: publicstatic Lis ...
- 删除本地git版本库中受版本控制的文件
git乱码解决方案汇总 乱码原因 搜索一番,发现git文件名.log乱码,是普遍问题,这其中有编码的原因,也有跨平台的原因.主要原因是Windows 系统中的Git对中文文件名采用不同的编码保存所致 ...
- 线程高级应用-心得8-java5线程并发库中同步集合Collections工具类的应用及案例分析
1. HashSet与HashMap的联系与区别? 区别:前者是单列后者是双列,就是hashmap有键有值,hashset只有键: 联系:HashSet的底层就是HashMap,可以参考HashSe ...
- 用CAS操作实现Go标准库中的Once
Go标准库中提供了Sync.Once来实现"只执行一次"的功能.学习了一下源代码,里面用的是经典的双重检查的模式: // Once is an object that will p ...
- 项目中通过Sorlj获取索引库中的数据
在开发项目中通过使用Solr所提供的Solrj(java客户端)获取索引库中的数据,这才是真正对项目起实质性作用的功能,提升平台的检索性能及检索结果的精确性 第一步,引入相关依赖的jar包 第二步,根 ...
- Git添加远程库和从远程库中获取(新手傻瓜式教学)
一. Git添加远程库 1.在本地新建一个文件夹,在该文件夹使用Git工具,运行$ git init,将该文件夹变为本地Git仓库,同时会生成一个隐藏的.git文件夹. 2.在该文件夹中用Not ...
- Git添加远程库和从远程库中获取
一. Git添加远程库 1. 在本地新建一个文件夹,在该文件夹使用Git工具,运行$ git init,将该文件夹变为本地Git仓库,同时会生成一个隐藏的.git文件夹. 2. 在该文件夹中用Note ...
随机推荐
- 如何用MathType 7输入连续几个数的和
在数学的学习中,我们经常需要使用求和符合来求连续几个数的和,那么作为专业的公式编辑器,如何输入连续几个数的求和呢? 具体步骤如下: 步骤一 打开专业的公式编辑软件MathType 7,用鼠标点击上方的 ...
- 「CF578F」 Mirror Box
description CF578F solution 考虑转化题目的要求 1.对于任意一条边,都存在一条从界垂直射入的光线,经过反射穿过这条边. 当图中有环时,环内的边一定不满足条件,而在不存在环时 ...
- Eclipse的环境配置
1.想要配置Eclipse的环境,就要先下载Eclipse,并安装它,不会下载安装的小伙伴可以点击下面给的链接,里面有我写的详细的教程,这里就不重复了 Eclipse下载与安装:https://blo ...
- sentinel--初级使用篇
1.官方资料 github官网地址:https://github.com/alibaba/Sentinel wiki:https://github.com/alibaba/Sentinel/wiki/ ...
- JavaSE 学习笔记06丨并发
Chapter 12. 并发 12.1 并发与并行 并发:指两个或多个事件在同一个时间段内发生. 并行:指两个或多个事件在同一时刻发生(同时发生). 在操作系统中,并发指的是在一段时间内宏观上有多个程 ...
- day99:MoFang:Flask-JSONRPC提供RPC接口&在APP进行窗口页面操作(窗口-帧-帧组)
目录 1.服务端基于Flask-JSONRPC提供RPC接口 1.Flask-JSONRPC简介 2.安装Flask-JSONRPC模块 3.快速实现一个测试的RPC接口 4.移动端访问测试接口 2. ...
- 在EXCEL带有字母的数字下拉如何能自动排序
在excel中0,1,2,3,4,5,6,7,8,9会自动排序,a,b,c,d,e,f,g.....会自动排序,所以可以分布来实现. 例如排序:fish1a.png,fish1b.png,fish1c ...
- 关于你天天见到的JDK、JRE和JVM
什么是JDK.JRE.JVM? 大家都知道电脑的操作系统是由汇编和C语言写出,因此操作系统无法直接识别其他语言.这时我们就需要为我们写的Java程序配备一名翻译官 ----- 编译环境,将Java程序 ...
- rest-framework:认证组件
一 认证简介: 只有认证通过的用户才能访问指定的url地址,比如:查询课程信息,需要登录之后才能查看,没有登录,就不能查看,这时候需要用到认证组件 二 局部使用 models.py class Use ...
- 新手上路A4——多JDK环境变量的配置
目录 配置单个JDK的方法 配置2+JDK的方法 方法 补充 检查JDK版本是否切换成功 前面讲了如何选择Java版本. 以及JDK8和JDK11的下载安装配置 有想法的人就开始发动他们优秀的小脑袋瓜 ...