如何在schema.json中为角度示意图“属性”定义默认变量?
我试图调查angular source code本身,但我无法弄明白。我发现如果使用关键字“$ source”,不知何故,它前面的字符串将被解析为某个值。
例如,“argv”和“projectName”是两个变量,当它们像这样写时,它们将被解析为实际值:
"project": {
"alias": "p",
"type": "string",
"description": "The name of the project.",
"$default": {
"$source": "projectName"
}
},
要么
"name": {
"type": "string",
"description": "The package name for the new schematic.",
"$default": {
"$source": "argv",
"index": 0
}
},
那么如何定义自己的变量呢?它们实际上是变量吗?还有哪些其他变量?
我还发现了另一个例子,如果我将它复制粘贴到我自己的项目中,它就无法工作:
"version": {
"type": "string",
"description": "The version of the Angular CLI to use.",
"visible": false,
"$default": {
"$source": "ng-cli-version"
}
},
根据我的观察,我希望这可以解决为一个值,但我得到了不应有的。
提前谢谢大家!
您定义的变量肯定取决于原理图的行为。例如,我有一个带有自定义变量的new application schematic,允许用户指定脚手架到应用程序中的身份验证类型:
要从命令行调用此原理图,用户将输入ng new my-application-schematic-with-sso --collection=@simple-schematic --authentication=SSO
(如果未明确提供命令行开关,x-prompt
会向用户提供选项列表。另请参阅Angular ng-new schema for style options。
"authentication": {
"description": "The authentication strategy to use",
"default": "None",
"x-prompt": {
"message": "Which authentication strategy would you like to use?",
"type": "list",
"items": [
{
"value": "None",
"label": "None"
},
{
"value": "SSO",
"label": "SSO"
}
]
}
},
此示意图还使用argv
模式捕获工作空间的名称:
"name": {
"description": "The name of the workspace",
"type": "string",
"$default": {
"$source": "argv",
"index": 0
}
},...
因此,调用此原理图的命令行语法看起来像ng new my-new-schematic --collection=@simple-schematic
,并将生成一个名为my-new-schematic的新工作区。由于未提供--authentication
标志,系统将提示用户选择None或SSO。
与您定义的模式和变量相关的一个重要行为可能导致您在原始问题中记录的未定义问题(尤其是当您的变量具有默认值时)未正确地将模式链接到逻辑示意图命令。
例如,schema
原理图对象的ng-new
属性指示如何将提供的CLI输入转换为传递给自定义原理图的corresponding object。
{
"$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
"extends": "@schematics/angular",
"schematics": {
"ng-new": {
"description": "new workspace",
"factory": "./ng-new",
"schema": "./ng-new/schema.json"
}
}
}
调试测试的两个不同屏幕截图取决于是否指定了schema
属性:
只需使用"default": "YOUR_VALUE"
但不要忘记之后运行npm run build
。