[英]angular2 how to change the default prefix of component to stop tslint warnings
看來,當我使用Angular cli創建一個Angular 2應用程序時。 我的默認組件前綴是AppComponent的app-root。 現在,當我將選擇器更改為其他名稱為“abc-root”時
@Component({
selector: 'abc-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
vscode警告我,
[tslint] The selector of the component "AppComponent" should have prefix "app"
您需要修改兩個文件tslint.json和.angular-cli.json,假設您要更改為myprefix :
在tslint.json文件中,只需修改以下2個屬性:
"directive-selector": [true, "attribute", "app", "camelCase"],
"component-selector": [true, "element", "app", "kebab-case"],
將“app”更改為“myprefix”
"directive-selector": [true, "attribute", "myprefix", "camelCase"],
"component-selector": [true, "element", "myprefix", "kebab-case"],
在angular.json文件中只需修改屬性前綴:( 對於小於6的角度版本,文件名為.angular-cli.json)
"app": [
...
"prefix": "app",
...
將“app”更改為“myprefix”
"app": [
...
"prefix": "myprefix",
...
如果在這種情況下你需要多個前綴@Salil Junior指出:
"component-selector": [true, "element", ["myprefix1", "myprefix2"], "kebab-case"],
如果使用Angular cli創建新項目,請使用此命令行選項
ng new project-name --prefix myprefix
angular-cli.json
:“prefix”:“defaultPrefix”,以便angular-cli將其用於生成組件。 Ajust tslint.json
是這樣的:
"directive-selector": [ true, "attribute", ["prefix1", "prefix2", "prefix3"], "camelCase" ], "component-selector": [ true, "element", ["prefix1", "prefix2", "prefix3"], "kebab-case" ],
實際上,使用Angular Cli,您只需更改位於根應用程序上的angular-cli.json
上的“apps”數組內的“prefix”標記。
改變“TheBestPrefix”,就像這樣。
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"test": "test.ts",
"tsconfig": "tsconfig.json",
"prefix": "TheBestPrefix",
"mobile": false,
"styles": [
"styles.css"
],
"scripts": [],
"environments": {
"source": "environments/environment.ts",
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
]
使用CLI生成新組件時, ng g component mycomponent
組件標記將具有以下名稱"TheBestPrefix-mycomponent"
對於angular 6/7
以上, /src
文件夾中將有一個tslint.json
,它包含組件和指令的tslist
規則。
{
"extends": "../tslint.json",
"rules": {
"directive-selector": [
true,
"attribute",
"directivePrefix",
"camelCase"
],
"component-selector": [
true,
"element",
"compoenent-prefix",
"kebab-case"
]
}
}
更改該文件將解決問題。
對於Angular CLI文件的最新版本,angular-cli.json已重命名為angular.json。 其他一切都是一樣的。
tslint.json
“component-selector”:[true,“element”,“app”,“kebab-case”]
這個'kebab-case'強制任何組件選擇器與這個' - '的情況。
例如,您可以像這樣選擇' app-test ',' app-my '。
至於你的錯誤問題,你必須用'app'啟動組件選擇器,就像我在例子中提到的那樣。
我不認為你應該在tslint.json中做任何改變,雖然它可以解決你的問題,但在tslint中改變是不好的做法。
謝謝
感謝@Aniruddha指出了角度7的變化:
在src/app/shared
創建tslint.json
以擴展app/tslint.json
:
{
"extends": "../../tslint.json",
"rules": {
"directive-selector": [
true,
"attribute",
"shared",
"camelCase"
],
"component-selector": [
true,
"element",
"shared",
"kebab-case"
]
}
}
有一件事 - 如果在app.component.spec中你從共享模塊中模擬一個組件,它會抱怨你的模擬選擇器以'shared'開頭而不是以'app'開頭。 我認為這是有道理的 - 我應該在他們來的模塊中創建我的模擬。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.