Angular Schematics. 定制化 angular.json 文件

4
当我使用原理图构建我的网站(ng new --collection=@foo/schematics myproject)时,一切都很好,除了一个问题:
生成的angular.json文件在样式数组中只包含一个样式文件,但我需要它包含多个自定义样式文件:
使用schematics构建后,当前的angular.json如下:
"build": {
  "options": {
    "styles: [
      "src/styles.scss"
    ]
  }
}

希望达成的目标:

"build": {
  "options": {
    "styles: [
      "src/styles.scss",
      "src/custom1.scss",
      "src/custom2.scss"
    ]
  }
}

我该如何告诉Angular Schematics例程我想要包含这些额外的样式表?

你的原理图是什么样子的? - eko
1个回答

6

我不确定这是否是最佳实践,但我最近也必须搞清楚这点...这是我所做的...

function updateAngularJson(options: any): Rule {
 return (host: Tree, context: SchematicContext) => {
  updateAngularJsonOptions(host, options);
  return host;
 }
}

function updateAngularJsonOptions(host, options) {
 var projectDir = (options.directory || options.name) + '/';
 var configPath = projectDir + 'angular.json';
 var workspace = getWorkspace(host, projectDirectory);

 if (host.exists(configPath)) {
  var currentAngularJson = host.read(configPath)!.toString('utf-8');
  var json = JSON.parse(currentAngularJson);
  var optionsJson = json['projects'][options.name]['architect']['build']['options'];
  optionsJson['assets'].push("src/custom1.scss");
  optionsJson['assets'].push("src/custom2.scss");
  json['projects'][options.name]['architect']['build']['options'] = optionsJson;
  host.overwrite(configPath, JSON.stringify(json, null, 2));
 } else {
  throw new SchematicsException('angular.json not found at ' + configPath);
 }
 return host;
}

请仔细检查上面的代码——由于某些原因,我无法复制/粘贴我的工作解决方案,所以我将其打出来以尝试协助……希望你可以从上面了解到思路……对我来说运行得很不错……


我喜欢新时代的开发正在从手动编码(大多数情况下)转向脚手架(大多数情况下),这一事实。 - vivekmore
1
对于我来说,脚手架填补了手工编码和开发人员文档之间的需求空缺。在我撰写框架和平台工具的特定职责中,我能够将通常需要编写的面向开发人员的文档减少约50%以上。我只需要提供一个生成代码示例页的一行命令,而不是一页页的代码示例,这太棒了! - mattezell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接