Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Schematics. Customizing the angular.json file

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?

like image 228
Scott B Avatar asked Oct 29 '25 13:10

Scott B


1 Answers

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...

like image 114
mattezell Avatar answered Nov 01 '25 05:11

mattezell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!