Angular CLI自定义构建器 [英] Angular CLI custom builder
问题描述
Angular CLI 6引入了一种新的构建器概念(又称为Architect Targets).
有几个预制的构建器与 @angular-devkit/build_angular
一样,但是不幸的是,没有文档可以解释如何创建自己的生成器.
Angular CLI 6 introduced a new concept of builders (aka Architect Targets).
There are a couple of prebuilt builders that come with @angular-devkit/build_angular
, but unfortunately there is no documentation that explains how to create your own builder.
如何创建自己的构建器(例如,修改基础的webpack配置)?
How do I create my own builder (for example to modify the underlying webpack configuration)?
推荐答案
更新:
Update:
For Angular 8+ read this AngularInDepth article.
可以在此处找到完整的文章.
为简单起见,我假设新的生成器是在Typescript中实现的,但是它也可以在纯JavaScript中实现.
For the sake of simplicity I assume that the new builder is implemented in Typescript, but it can be implemented in pure JavaScript as well.
- 在项目的根目录中为自定义构建器(例如 custom-builders )创建目录(或者将其安装为此处查看示例a>.
- 根据您定义的 schema.json 定义您的 schema.d.ts .在此处查看示例.
-
在 my-cool-builder/index.ts 中添加您的构建器.构建器必须实现以下接口:
- Create a directory for your custom builders (for example custom-builders) in the root of your project (or alternatively install it as a local npm module)
- Inside the directory create a file called builders.json, index.ts and package.json that contains
builders
entry pointing to builders.json - Inside custom-builders create a directory for the builder you want to implement (say, custom-builders/my-cool-builder
- Add index.ts, schema.json and schema.d.ts to my-cool-builder directory
- Populate schema.json with the schema of your builder options. See an example here.
- Define your schema.d.ts according to the schema.json you defined. See an example here.
Implement your builder in my-cool-builder/index.ts. The builder has to implement the following interface:
export interface Builder<OptionsT> {
run(builderConfig: BuilderConfiguration<Partial<OptionsT>>): Observable<BuildEvent>;
}
BuildEvent
是这样的:
export interface BuildEvent {
success: boolean;
}
BuilderConfiguration
是这个:
export interface BuilderConfiguration<OptionsT = {}> {
root: Path;
sourceRoot?: Path;
projectType: string;
builder: string;
options: OptionsT;
}
OptionsT
是您在 schema.d.ts
您可以使用 browser
建筑师目标作为参考.
You can use browser
architect target as a reference.
实施后,将您的构建器添加到 builders.json :
Once implemented, add your builder to builders.json:
{
"$schema": "@angular-devkit/architect/src/builders-schema.json",
"builders": {
"cool-builder": {
"class": "./my-cool-builder",
"schema": "./my-cool-builder/schema.json",
"description": "My cool builder that builds things up"
}
}
}
用法:
在您的 angular.json 中:
"architect": {
...
"build": {
"builder": "./custom-builders:cool-builder"
"options": {
your options here
}
示例
有关完整示例,请查看以下库: https://github.com/meltedspark/angular-建设者
这篇关于Angular CLI自定义构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!