Skip to content

Commit 957af11

Browse files
committed
feat(@schematics/angular): use library builder and add entry-point schematic
Update the library schematic to configure @angular/build:library with a single tsconfig.lib.json instead of @angular/build:ng-packagr, and add an entry-point schematic to generate secondary entry points under src/<name>/.
1 parent d502a5e commit 957af11

20 files changed

Lines changed: 884 additions & 155 deletions

‎packages/angular/cli/lib/config/workspace-schema.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,9 @@
147147
"@schematics/angular:directive": {
148148
"$ref": "../../../../schematics/angular/directive/schema.json"
149149
},
150+
"@schematics/angular:entry-point": {
151+
"$ref": "../../../../schematics/angular/entry-point/schema.json"
152+
},
150153
"@schematics/angular:enum": {
151154
"$ref": "../../../../schematics/angular/enum/schema.json"
152155
},

‎packages/angular/cli/src/command-builder/utilities/schematic-engine-host.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,12 @@ const legacyModules: Record<string, unknown> = {
117117
},
118118
'@schematics/angular/utility/project': {
119119
buildDefaultPath(project: { sourceRoot?: string; root: string; projectType: string }): string {
120-
const root = project.sourceRoot ? `/${project.sourceRoot}/` : `/${project.root}/src/`;
120+
const isLibraryAtRoot =
121+
project.projectType === 'library' && project.sourceRoot === project.root;
122+
const root =
123+
project.sourceRoot && !isLibraryAtRoot
124+
? `/${project.sourceRoot}/`
125+
: `/${project.root}/src/`;
121126

122127
return `${root}${project.projectType === 'application' ? 'app' : 'lib'}`;
123128
},

‎packages/schematics/angular/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ for generating an Angular application.
1313
| component | Creates a new, generic component definition in the given project |
1414
| directive | Creates a new, generic directive definition in the given project |
1515
| enum | Generates a new, generic enum definition in the given project |
16+
| entry-point | Creates a new secondary entry point in an Angular library project |
1617
| guard | Generates a new, generic route guard definition in the given project |
1718
| interceptor | Creates a new, generic interceptor definition in the given project |
1819
| interface | Creates a new, generic interface definition in the given project |

‎packages/schematics/angular/collection.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,11 @@
111111
"schema": "./library/schema.json",
112112
"description": "Generate a library project for Angular."
113113
},
114+
"entry-point": {
115+
"factory": "./entry-point",
116+
"schema": "./entry-point/schema.json",
117+
"description": "Generate a secondary entry point for an Angular library."
118+
},
114119
"web-worker": {
115120
"factory": "./web-worker",
116121
"schema": "./web-worker/schema.json",
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
/*
2+
* Public API Surface of <%= dasherize(name) %>
3+
*/
4+
5+
export * from './<%= isPrimary ? 'lib/' : '' %><%= dasherize(name) %>';<% if (!standalone) { %>
6+
export * from './<%= isPrimary ? 'lib/' : '' %><%= dasherize(name) %>-module';<% } %>
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import { type JsonObject, type JsonValue, isJsonObject } from '@angular-devkit/core';
10+
import {
11+
type Rule,
12+
SchematicsException,
13+
type Tree,
14+
apply,
15+
applyTemplates,
16+
chain,
17+
mergeWith,
18+
move,
19+
noop,
20+
schematic,
21+
strings,
22+
url,
23+
} from '@angular-devkit/schematics';
24+
import { basename, join, relative } from 'node:path/posix';
25+
import { JSONFile } from '../utility/json-file';
26+
import { createProjectSchematic } from '../utility/project';
27+
import { Builders, ProjectType } from '../utility/workspace-models';
28+
import type { Schema as EntryPointOptions } from './schema';
29+
30+
function updateTsConfig(packageName: string, ...paths: string[]): Rule {
31+
return (host: Tree) => {
32+
if (!host.exists('tsconfig.json')) {
33+
return host;
34+
}
35+
36+
const file = new JSONFile(host, 'tsconfig.json');
37+
const jsonPath = ['compilerOptions', 'paths', packageName];
38+
const value = file.get(jsonPath);
39+
file.modify(jsonPath, Array.isArray(value) ? Array.from(new Set([...value, ...paths])) : paths);
40+
};
41+
}
42+
43+
export default createProjectSchematic<EntryPointOptions>((options, { project, tree }) => {
44+
if (project.extensions['projectType'] !== ProjectType.Library) {
45+
throw new SchematicsException(`Project "${options.project}" is not a library project.`);
46+
}
47+
48+
const buildTarget = project.targets.get('build');
49+
if (buildTarget?.builder !== Builders.BuildLibrary) {
50+
throw new SchematicsException(
51+
`Project "${options.project}" does not use the "${Builders.BuildLibrary}" builder.`,
52+
);
53+
}
54+
55+
if (options.name === 'package.json') {
56+
throw new SchematicsException('Entry point name "package.json" is reserved.');
57+
}
58+
59+
const libDir = project.root;
60+
const packageJsonPath = join(libDir, 'package.json');
61+
if (!tree.exists(packageJsonPath)) {
62+
throw new SchematicsException(`Could not find package.json at "${packageJsonPath}".`);
63+
}
64+
65+
const packageJson = new JSONFile(tree, packageJsonPath);
66+
const rawPackageName = packageJson.get(['name']);
67+
const packageName =
68+
typeof rawPackageName === 'string' && rawPackageName
69+
? rawPackageName
70+
: strings.dasherize(options.project);
71+
72+
const isPrimary = options.name === '.';
73+
const entryFile = (options.entryFile ?? 'public-api').replace(/\.ts$/i, '');
74+
const entryPointDir = join(libDir, options.name, 'src');
75+
const exportKey = isPrimary ? '.' : `./${options.name}`;
76+
const exportTarget = `./${relative(libDir, join(entryPointDir, `${entryFile}.ts`))}`;
77+
78+
const existingExports = (packageJson.get(['exports']) as JsonValue | undefined) ?? null;
79+
let exportsObject: JsonObject = {};
80+
if (typeof existingExports === 'string' || Array.isArray(existingExports)) {
81+
exportsObject = { '.': existingExports };
82+
} else if (isJsonObject(existingExports)) {
83+
const keys = Object.keys(existingExports);
84+
if (keys.some((k) => k.startsWith('.'))) {
85+
exportsObject = { ...existingExports };
86+
} else if (keys.length > 0) {
87+
exportsObject = { '.': existingExports };
88+
}
89+
}
90+
91+
if (Object.prototype.hasOwnProperty.call(exportsObject, exportKey)) {
92+
throw new SchematicsException(
93+
`Entry point "${exportKey}" already exists in "${packageJsonPath}".`,
94+
);
95+
}
96+
97+
if (
98+
isJsonObject(existingExports) &&
99+
Object.keys(existingExports).some((k) => k.startsWith('.'))
100+
) {
101+
packageJson.modify(['exports', exportKey], exportTarget, false);
102+
} else {
103+
packageJson.modify(
104+
['exports'],
105+
{
106+
...exportsObject,
107+
[exportKey]: exportTarget,
108+
},
109+
false,
110+
);
111+
}
112+
113+
const prefix = (options.prefix ?? project.prefix) || 'lib';
114+
const sourceDir = isPrimary ? join(entryPointDir, 'lib') : entryPointDir;
115+
const artifactName = isPrimary
116+
? /^@.*\/.*/.test(options.project)
117+
? options.project.split('/')[1]
118+
: options.project
119+
: basename(options.name);
120+
121+
const buildOptions = buildTarget.options;
122+
const distRoot =
123+
typeof buildOptions?.['outputPath'] === 'string'
124+
? buildOptions['outputPath']
125+
: join('dist', options.project);
126+
127+
const tsConfigPathKey = isPrimary ? packageName : `${packageName}/*`;
128+
const tsConfigPathTarget = `./${join(distRoot, isPrimary ? '.' : '*')}`;
129+
130+
const standalone = options.standalone ?? true;
131+
132+
const templateSource = apply(url('../entry-point/files'), [
133+
applyTemplates({
134+
...strings,
135+
...options,
136+
isPrimary,
137+
standalone,
138+
name: artifactName,
139+
entryFile,
140+
}),
141+
move(entryPointDir),
142+
]);
143+
144+
return chain([
145+
mergeWith(templateSource),
146+
options.skipTsConfig ? noop() : updateTsConfig(tsConfigPathKey, tsConfigPathTarget),
147+
standalone
148+
? noop()
149+
: schematic('module', {
150+
name: artifactName,
151+
commonModule: false,
152+
flat: true,
153+
path: sourceDir,
154+
project: options.project,
155+
// Explicitly set the `typeSeparator` this also ensures that the generated files are valid even if the `module` schematic
156+
// inherits its `typeSeparator` from the workspace.
157+
typeSeparator: '-',
158+
}),
159+
schematic('component', {
160+
name: artifactName,
161+
selector: `${prefix}-${strings.dasherize(artifactName)}`,
162+
inlineStyle: true,
163+
inlineTemplate: true,
164+
flat: true,
165+
path: sourceDir,
166+
export: true,
167+
standalone,
168+
skipTests: options.skipTests,
169+
project: options.project,
170+
// Explicitly set an empty `type` and `exportDefault: false` since they don't necessarily make
171+
// sense in a library and ensure that the generated files match the entry-point exports even
172+
// if the `component` schematic inherits options from the workspace.
173+
type: '',
174+
exportDefault: false,
175+
}),
176+
]);
177+
});

0 commit comments

Comments
 (0)