在使用 Angular CLI 开发 Angular 应用时,用 ng generate 命令生成的目标(组件,服务等)的命令方式都是在指定的名字前再加上一个 app 前缀。如何改变这个前缀呢?
使用 –prefix 参数
使用 ng new 命令生成应用时,可以带上一个参数 –prefix ,这个参数会在后续的 ng generate 命令中起作用,会改变默认的 app 前缀。例如:
新建一个 hohistar-todo-app 的应用,指定使用 hohistar 作为前缀
1
| ng new hohistar-todo-app --prefix=hohistar
|
然后进入项目目录,增加一个组件,
1
| ng g c components/layout/header
|
系统显示
1 2 3 4 5
| CREATE src/app/components/layout/header/header.component.html (21 bytes) CREATE src/app/components/layout/header/header.component.spec.ts (628 bytes) CREATE src/app/components/layout/header/header.component.ts (274 bytes) CREATE src/app/components/layout/header/header.component.css (0 bytes) UPDATE src/app/app.module.ts (493 bytes)
|
可以看到,在 src/app/components/layout/header 目录下生成了组件相关的文件, 打开 header.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import { Component, OnInit } from '@angular/core';
@Component({ selector: 'hohistar-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
|
注意 selector 的值已经加上指定的前缀: hohistar-header ,而不是通常的 app-header 。
直接在配置文件中改
实际上,默认的前缀是保存在 angular.json 文件中的, 打开项目目录下的 angular.json 文件
1 2 3 4 5 6 7 8 9 10 11 12 13
| { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "hohistar-todo-app": { "projectType": "application", "schematics": {}, "root": "", "sourceRoot": "src", "prefix": "hohistar",
...
|
prefix 保存的就是在命令行参数中指定的值。