The task is to extend ng-new schematics and add some dependencies like @angular/material and Lumberjack etc.
I found one article where author suggested to use some utilities provided in package '@schematics/angular/utility/dependencies'. I tried and it is working fine. Below is the code:
function addLibrary(_options: any): Rule {
return (_tree: Tree, _context: SchematicContext) => {
const dep: NodeDependency = {
type: NodeDependencyType.Dev,
name: '@angular/material',
version: '11.2.8',
overwrite: true,
};
addPackageJsonDependency(_, dep);
const installTaskId = _context.addTask(new NodePackageInstallTask(), []);
return _tree
};
}
However, in the same article author warned that
The helper functions I present you in this article are neither documented nor officially supported, and they may change in the future
So my question is, is there any official and reliable way to add package dependencies in angular schematics? specially when extending ng-new schematic?
I would say you are safe to use that function as Angular
internally uses that function across all their internal packages.
Angular CLI packages has so many of these functions and its difficult to document each of them(personal opinion) and that does not mean you cannot use that.
However for any reason if you don't want to use that function then you can write your own which modify the package.json
file using Tree
.
function addPackageToPackageJson(host: Tree, pkg: string, version: string): Tree {
if (host.exists("package.json")) {
const sourceText = host.read("package.json")!.toString("utf-8");
const json = JSON.parse(sourceText) as PackageJson;
if (!json.dependencies) {
json.dependencies = {};
}
if (!json.dependencies[pkg]) {
json.dependencies[pkg] = version;
json.dependencies = sortObjectByKeys(json.dependencies);
}
host.overwrite("package.json", JSON.stringify(json, null, 2));
}
return host;
}
Reference:- https://github.com/angular/components/blob/HEAD/src/cdk/schematics/ng-add/package-config.ts#L24