Skip to content

Commit a32141c

Browse files
committed
fixup! feat(@schematics/angular): use library builder and add entry-point schematic
1 parent c033dbc commit a32141c

6 files changed

Lines changed: 144 additions & 72 deletions

File tree

‎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/entry-point/index.ts‎

Lines changed: 43 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import {
2424
import { basename, join, relative } from 'node:path/posix';
2525
import { JSONFile } from '../utility/json-file';
2626
import { createProjectSchematic } from '../utility/project';
27-
import { ProjectType } from '../utility/workspace-models';
27+
import { Builders, ProjectType } from '../utility/workspace-models';
2828
import type { Schema as EntryPointOptions } from './schema';
2929

3030
function updateTsConfig(packageName: string, ...paths: string[]): Rule {
@@ -45,10 +45,21 @@ export default createProjectSchematic<EntryPointOptions>((options, { project, tr
4545
throw new SchematicsException(`Project "${options.project}" is not a library project.`);
4646
}
4747

48-
if (options.name === 'lib' || options.name.startsWith('lib/')) {
48+
const buildTarget = project.targets.get('build');
49+
if (buildTarget?.builder !== Builders.BuildLibrary) {
4950
throw new SchematicsException(
50-
`Entry point name "${options.name}" cannot be "lib" or start with "lib/" ` +
51-
'as it conflicts with the primary entry point source directory.',
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+
if (options.name.split('/').includes('lib')) {
60+
throw new SchematicsException(
61+
`Entry point name "${options.name}" cannot be "lib" or contain a "lib" segment ` +
62+
'as it conflicts with the entry point source directory.',
5263
);
5364
}
5465

@@ -66,7 +77,7 @@ export default createProjectSchematic<EntryPointOptions>((options, { project, tr
6677
: strings.dasherize(options.project);
6778

6879
const isPrimary = options.name === '.';
69-
const entryFile = (options.entryFile ?? 'public-api').replace(/\.[cm]?ts$/i, '');
80+
const entryFile = (options.entryFile ?? 'public-api').replace(/\.ts$/i, '');
7081
const sourceRoot = project.sourceRoot ?? join(libDir, 'src');
7182
const entryPointDir = join(sourceRoot, options.name);
7283
const exportKey = isPrimary ? '.' : `./${options.name}`;
@@ -95,41 +106,42 @@ export default createProjectSchematic<EntryPointOptions>((options, { project, tr
95106
isJsonObject(existingExports) &&
96107
Object.keys(existingExports).some((k) => k.startsWith('.'))
97108
) {
98-
packageJson.modify(['exports', exportKey], exportTarget);
109+
packageJson.modify(['exports', exportKey], exportTarget, false);
99110
} else {
100-
packageJson.modify(['exports'], {
101-
...exportsObject,
102-
[exportKey]: exportTarget,
103-
});
111+
packageJson.modify(
112+
['exports'],
113+
{
114+
...exportsObject,
115+
[exportKey]: exportTarget,
116+
},
117+
false,
118+
);
104119
}
105120

106-
const prefix = options.prefix ?? project.prefix ?? 'lib';
121+
const prefix = (options.prefix ?? project.prefix) || 'lib';
107122
const sourceDir = join(entryPointDir, 'lib');
108123
const artifactName = isPrimary
109124
? /^@.*\/.*/.test(options.project)
110125
? options.project.split('/')[1]
111126
: options.project
112127
: basename(options.name);
113128

114-
const buildOptions = project.targets.get('build')?.options;
115-
let distRoot: string;
116-
if (typeof buildOptions?.['outputPath'] === 'string') {
117-
distRoot = buildOptions['outputPath'];
118-
} else {
119-
let folderName = options.project.startsWith('@') ? options.project.slice(1) : options.project;
120-
if (/[A-Z]/.test(folderName)) {
121-
folderName = strings.dasherize(folderName);
122-
}
123-
distRoot = `dist/${folderName}`;
124-
}
129+
const buildOptions = buildTarget.options;
130+
const distRoot =
131+
typeof buildOptions?.['outputPath'] === 'string'
132+
? buildOptions['outputPath']
133+
: join('dist', options.project);
134+
135+
const tsConfigPathKey = isPrimary ? packageName : `${packageName}/*`;
136+
const tsConfigPathTarget = `./${join(distRoot, isPrimary ? '.' : '*')}`;
125137

126-
const tsConfigPathKey = isPrimary ? packageName : `${packageName}/${options.name}`;
127-
const tsConfigPathTarget = `./${join(distRoot, options.name)}`;
138+
const standalone = options.standalone ?? true;
128139

129-
const templateSource = apply(url('./files'), [
140+
const templateSource = apply(url('../entry-point/files'), [
130141
applyTemplates({
131142
...strings,
132143
...options,
144+
standalone,
133145
name: artifactName,
134146
entryFile,
135147
}),
@@ -139,7 +151,7 @@ export default createProjectSchematic<EntryPointOptions>((options, { project, tr
139151
return chain([
140152
mergeWith(templateSource),
141153
options.skipTsConfig ? noop() : updateTsConfig(tsConfigPathKey, tsConfigPathTarget),
142-
options.standalone
154+
standalone
143155
? noop()
144156
: schematic('module', {
145157
name: artifactName,
@@ -159,13 +171,14 @@ export default createProjectSchematic<EntryPointOptions>((options, { project, tr
159171
flat: true,
160172
path: sourceDir,
161173
export: true,
162-
standalone: options.standalone,
174+
standalone,
163175
skipTests: options.skipTests,
164176
project: options.project,
165-
// Explicitly set an empty `type` since it doesn't necessarily make sense in a library.
166-
// This also ensures that the generated files are valid even if the `component` schematic
167-
// inherits its `type` from the workspace.
177+
// Explicitly set an empty `type` and `exportDefault: false` since they don't necessarily make
178+
// sense in a library and ensure that the generated files match the entry-point exports even
179+
// if the `component` schematic inherits options from the workspace.
168180
type: '',
181+
exportDefault: false,
169182
}),
170183
]);
171184
});

‎packages/schematics/angular/entry-point/index_spec.ts‎

Lines changed: 84 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -89,9 +89,7 @@ describe('EntryPoint Schematic', () => {
8989
expect(pkgJson.exports['./feature/sub']).toBe('./src/feature/sub/public-api.ts');
9090

9191
const tsConfigJson = getJsonFileContent(tree, '/tsconfig.json');
92-
expect(tsConfigJson.compilerOptions.paths['foo/feature/sub']).toEqual([
93-
'./dist/foo/feature/sub',
94-
]);
92+
expect(tsConfigJson.compilerOptions.paths['foo/*']).toEqual(['./dist/foo/*']);
9593
});
9694

9795
it('should support custom entryFile option', async () => {
@@ -133,6 +131,7 @@ describe('EntryPoint Schematic', () => {
133131
'.': './src/public-api.ts',
134132
'./secondary': './src/secondary/public-api.ts',
135133
});
134+
expect(Object.keys(pkgJson)[0]).toBe('name');
136135
});
137136

138137
it('should convert string exports in library package.json to an exports object', async () => {
@@ -177,23 +176,23 @@ describe('EntryPoint Schematic', () => {
177176
});
178177
});
179178

180-
it('should add paths mapping to root tsconfig.json', async () => {
179+
it('should add wildcard paths mapping to root tsconfig.json', async () => {
181180
const tree = await schematicRunner.runSchematic('entry-point', defaultOptions, workspaceTree);
182181

183182
const tsConfigJson = getJsonFileContent(tree, '/tsconfig.json');
184183
expect(tsConfigJson.compilerOptions.paths['foo']).toEqual(['./dist/foo']);
185-
expect(tsConfigJson.compilerOptions.paths['foo/secondary']).toEqual(['./dist/foo/secondary']);
184+
expect(tsConfigJson.compilerOptions.paths['foo/*']).toEqual(['./dist/foo/*']);
186185
});
187186

188187
it('should not duplicate existing paths mapping in root tsconfig.json', async () => {
189188
const tsConfig = getJsonFileContent(workspaceTree, '/tsconfig.json');
190-
tsConfig.compilerOptions.paths['foo/secondary'] = ['./dist/foo/secondary'];
189+
tsConfig.compilerOptions.paths['foo/*'] = ['./dist/foo/*'];
191190
workspaceTree.overwrite('/tsconfig.json', JSON.stringify(tsConfig, null, 2));
192191

193192
const tree = await schematicRunner.runSchematic('entry-point', defaultOptions, workspaceTree);
194193

195194
const tsConfigJson = getJsonFileContent(tree, '/tsconfig.json');
196-
expect(tsConfigJson.compilerOptions.paths['foo/secondary']).toEqual(['./dist/foo/secondary']);
195+
expect(tsConfigJson.compilerOptions.paths['foo/*']).toEqual(['./dist/foo/*']);
197196
});
198197

199198
it('should respect custom outputPath in angular.json for tsconfig paths mapping', async () => {
@@ -204,9 +203,7 @@ describe('EntryPoint Schematic', () => {
204203
const tree = await schematicRunner.runSchematic('entry-point', defaultOptions, workspaceTree);
205204

206205
const tsConfigJson = getJsonFileContent(tree, '/tsconfig.json');
207-
expect(tsConfigJson.compilerOptions.paths['foo/secondary']).toEqual([
208-
'./custom-dist/foo/secondary',
209-
]);
206+
expect(tsConfigJson.compilerOptions.paths['foo/*']).toEqual(['./custom-dist/foo/*']);
210207
});
211208

212209
it('should respect custom sourceRoot in angular.json', async () => {
@@ -239,7 +236,7 @@ describe('EntryPoint Schematic', () => {
239236
);
240237

241238
const tsConfigJson = getJsonFileContent(tree, '/tsconfig.json');
242-
expect(tsConfigJson.compilerOptions.paths['foo/secondary']).toBeUndefined();
239+
expect(tsConfigJson.compilerOptions.paths['foo/*']).toBeUndefined();
243240
});
244241

245242
it('should inherit prefix from the library project in angular.json', async () => {
@@ -268,6 +265,17 @@ describe('EntryPoint Schematic', () => {
268265
expect(componentContent).toContain("selector: 'custom-secondary'");
269266
});
270267

268+
it('should fallback to "lib" prefix when project prefix is empty in angular.json', async () => {
269+
const angularJson = getJsonFileContent(workspaceTree, '/angular.json');
270+
angularJson.projects.foo.prefix = '';
271+
workspaceTree.overwrite('/angular.json', JSON.stringify(angularJson, null, 2));
272+
273+
const tree = await schematicRunner.runSchematic('entry-point', defaultOptions, workspaceTree);
274+
275+
const componentContent = tree.readContent('/projects/foo/src/secondary/lib/secondary.ts');
276+
expect(componentContent).toContain("selector: 'lib-secondary'");
277+
});
278+
271279
it('should allow overriding prefix via option', async () => {
272280
const tree = await schematicRunner.runSchematic(
273281
'entry-point',
@@ -316,8 +324,8 @@ describe('EntryPoint Schematic', () => {
316324
});
317325

318326
const tsConfigJson = getJsonFileContent(tree, '/tsconfig.json');
319-
expect(tsConfigJson.compilerOptions.paths['@my-scope/my-lib/secondary']).toEqual([
320-
'./dist/my-scope/my-lib/secondary',
327+
expect(tsConfigJson.compilerOptions.paths['@my-scope/my-lib/*']).toEqual([
328+
'./dist/my-scope/my-lib/*',
321329
]);
322330
});
323331

@@ -335,6 +343,24 @@ describe('EntryPoint Schematic', () => {
335343
expect(tree.files).not.toContain('/projects/foo/src/secondary/lib/secondary.spec.ts');
336344
});
337345

346+
it('should not be affected by workspace component schematic type and exportDefault defaults', async () => {
347+
const angularJson = getJsonFileContent(workspaceTree, '/angular.json');
348+
angularJson.schematics = {
349+
'@schematics/angular:component': {
350+
type: 'component',
351+
exportDefault: true,
352+
},
353+
};
354+
workspaceTree.overwrite('/angular.json', JSON.stringify(angularJson, null, 2));
355+
356+
const tree = await schematicRunner.runSchematic('entry-point', defaultOptions, workspaceTree);
357+
358+
expect(tree.files).toContain('/projects/foo/src/secondary/lib/secondary.ts');
359+
const componentContent = tree.readContent('/projects/foo/src/secondary/lib/secondary.ts');
360+
expect(componentContent).toContain('export class Secondary');
361+
expect(componentContent).not.toContain('export default');
362+
});
363+
338364
describe('standalone=false', () => {
339365
it('should create an NgModule and export it in the entry file', async () => {
340366
const tree = await schematicRunner.runSchematic(
@@ -394,6 +420,16 @@ describe('EntryPoint Schematic', () => {
394420
).toBeRejectedWithError('Project "my-app" is not a library project.');
395421
});
396422

423+
it('should throw if the library project does not use @angular/build:library', async () => {
424+
const angularJson = getJsonFileContent(workspaceTree, '/angular.json');
425+
angularJson.projects.foo.architect.build.builder = '@angular/build:ng-packagr';
426+
workspaceTree.overwrite('/angular.json', JSON.stringify(angularJson, null, 2));
427+
428+
await expectAsync(
429+
schematicRunner.runSchematic('entry-point', defaultOptions, workspaceTree),
430+
).toBeRejectedWithError('Project "foo" does not use the "@angular/build:library" builder.');
431+
});
432+
397433
it('should throw if the library package.json is missing', async () => {
398434
workspaceTree.delete('/projects/foo/package.json');
399435

@@ -402,32 +438,50 @@ describe('EntryPoint Schematic', () => {
402438
).toBeRejectedWithError('Could not find package.json at "projects/foo/package.json".');
403439
});
404440

405-
it('should throw if the entry-point name is "lib" or starts with "lib/"', async () => {
441+
it('should throw if the entry-point name is "package.json"', async () => {
406442
await expectAsync(
407443
schematicRunner.runSchematic(
408444
'entry-point',
409445
{
410-
name: 'lib',
446+
name: 'package.json',
411447
project: 'foo',
412448
},
413449
workspaceTree,
414450
),
415-
).toBeRejectedWithError(
416-
'Entry point name "lib" cannot be "lib" or start with "lib/" as it conflicts with the primary entry point source directory.',
417-
);
451+
).toBeRejectedWithError('Entry point name "package.json" is reserved.');
452+
});
418453

419-
await expectAsync(
420-
schematicRunner.runSchematic(
421-
'entry-point',
422-
{
423-
name: 'lib/sub',
424-
project: 'foo',
425-
},
426-
workspaceTree,
427-
),
428-
).toBeRejectedWithError(
429-
'Entry point name "lib/sub" cannot be "lib" or start with "lib/" as it conflicts with the primary entry point source directory.',
430-
);
454+
it('should throw if the entry-point name is "lib" or contains a "lib" segment', async () => {
455+
for (const invalidName of ['lib', 'lib/sub', 'feature/lib', 'feature/lib/sub']) {
456+
await expectAsync(
457+
schematicRunner.runSchematic(
458+
'entry-point',
459+
{
460+
name: invalidName,
461+
project: 'foo',
462+
},
463+
workspaceTree,
464+
),
465+
).toBeRejectedWithError(
466+
`Entry point name "${invalidName}" cannot be "lib" or contain a "lib" segment ` +
467+
'as it conflicts with the entry point source directory.',
468+
);
469+
}
470+
});
471+
472+
it('should reject invalid entry-point names via schema validation', async () => {
473+
for (const invalidName of ['.', '../foo', 'foo..bar', '/secondary', 'secondary/', './sub']) {
474+
await expectAsync(
475+
schematicRunner.runSchematic(
476+
'entry-point',
477+
{
478+
name: invalidName,
479+
project: 'foo',
480+
},
481+
workspaceTree,
482+
),
483+
).toBeRejected();
484+
}
431485
});
432486

433487
it('should throw if the entry point already exists in package.json exports', async () => {

‎packages/schematics/angular/entry-point/schema.json‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
{
22
"$schema": "http://json-schema.org/draft-07/schema",
3-
"$id": "SchematicsEntryPoint",
4-
"title": "Entry Point Options Schema",
3+
"$id": "SchematicsAngularEntryPoint",
4+
"title": "Angular Entry Point Options Schema",
55
"type": "object",
66
"description": "Creates a new secondary entry point in an Angular library project.",
77
"additionalProperties": false,
88
"properties": {
99
"name": {
1010
"type": "string",
1111
"description": "The name of the secondary entry point (for example, 'testing' or 'feature/sub').",
12-
"pattern": "^(?:\\.|[a-zA-Z0-9-~][a-zA-Z0-9-._~]*(?:/[a-zA-Z0-9-~][a-zA-Z0-9-._~]*)*)$",
12+
"pattern": "^(?!.*\\.\\.)[a-zA-Z0-9-~][a-zA-Z0-9-._~]*(?:/[a-zA-Z0-9-~][a-zA-Z0-9-._~]*)*$",
1313
"$default": {
1414
"$source": "argv",
1515
"index": 0
@@ -18,7 +18,7 @@
1818
},
1919
"project": {
2020
"type": "string",
21-
"description": "The name of the library project.",
21+
"description": "The name of the library project where the secondary entry point should be added. If not specified, the CLI will determine the project from the current directory.",
2222
"$default": {
2323
"$source": "projectName"
2424
}
@@ -44,12 +44,12 @@
4444
"skipTests": {
4545
"type": "boolean",
4646
"default": false,
47-
"description": "Do not create \"spec.ts\" test files for the new secondary entry point."
47+
"description": "Do not create `spec.ts` test files for the new secondary entry point."
4848
},
4949
"skipTsConfig": {
5050
"type": "boolean",
5151
"default": false,
52-
"description": "Do not update \"tsconfig.json\" to add a path mapping for the new secondary entry point."
52+
"description": "Do not update `tsconfig.json` to add a path mapping for the new secondary entry point."
5353
}
5454
},
5555
"required": ["name", "project"]

0 commit comments

Comments
 (0)