4

When I build my site with schematics (ng new --collection=@foo/schematics myproject), everything works fine, except one thing:

The resulting angular.json file only includes a single style file in the styles array, I need it to include multiple custom style files:

Current angular.json after ng new schematics build:

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

Desired:

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

How can I tell the angular schematics routine that I want to include these additional stylesheets?

Scott B
  • 38,833
  • 65
  • 160
  • 266

1 Answers1

6

I'm not sure if this is the best practice or not, but I recently had to figure this out also... Here's what I did...

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;
}

Double check the code above - I can't copy/paste my working solution for reasons, so I've typed this out for the purpose of trying to assist.. Hopefully you get the idea from the above... Works pretty well for me...

mattezell
  • 607
  • 1
  • 6
  • 13
  • I love the fact the development in the new era is shifting from manual coding (most of the time) to scaffolding (most of the time) – vivekmore Mar 29 '19 at 12:08
  • 1
    @vivekmore, for me the scaffolding fills a need somewhere between manual coding and developer documentation. In my particular role of writing framework and platform tools, I'm able to reduce the developer targeting documentation that I'd typically have to write by ~50%+. Instead of a page of code samples, I'm able to provide a one-liner that generates the page of code sample, which is awesome! – mattezell Apr 16 '19 at 14:53