Skip to content

Commit 047d0fc

Browse files
committed
fix(@schematics/angular): align sourceRoot and tsconfig includes in use-library-builder
Update `sourceRoot` to match `root` when migrating libraries with the default `<root>/src` or omitted `sourceRoot`, and broaden `src/**` `include` globs in the library's TypeScript configs so secondary entry points generated outside `src/` are covered by TypeScript and test discovery.
1 parent 957af11 commit 047d0fc

2 files changed

Lines changed: 232 additions & 4 deletions

File tree

‎packages/schematics/angular/migrations/use-library-builder/migration.ts‎

Lines changed: 117 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
import { JSONFile } from '../../utility/json-file';
2525
import { latestVersions } from '../../utility/latest-versions';
2626
import {
27+
type ProjectDefinition,
2728
type TargetDefinition,
2829
allTargetOptions,
2930
allWorkspaceTargets,
@@ -365,20 +366,22 @@ function migrateTargetOptions(
365366
/**
366367
* Migrates a single library project's `build` target from `ng-packagr` to `@angular/build:library`,
367368
* transferring configuration options to `angular.json`, writing entry points to `package.json#exports`,
368-
* and cleaning up obsolete `ng-packagr` configuration files.
369+
* aligning `sourceRoot` and TypeScript `include` globs, and cleaning up obsolete `ng-packagr`
370+
* configuration files.
369371
*
370-
* @param projectRoot The root directory of the library project.
372+
* @param project The library project definition in `angular.json`.
371373
* @param buildTarget The library's `build` target definition in `angular.json`.
372374
* @param tree The virtual file system tree.
373375
* @param context The schematic execution context.
374376
* @returns `true` if the library target was migrated, or `false` if it was skipped.
375377
*/
376378
function updateLibraryTarget(
377-
projectRoot: string,
379+
project: ProjectDefinition,
378380
buildTarget: TargetDefinition,
379381
tree: Tree,
380382
context: SchematicContext,
381383
): boolean {
384+
const projectRoot = project.root;
382385
const normalizedProjectRoot = normalizeRelativePath(projectRoot);
383386
let primaryProjectFile =
384387
typeof buildTarget.options?.['project'] === 'string'
@@ -470,6 +473,18 @@ function updateLibraryTarget(
470473

471474
migrateTargetOptions(normalizedProjectRoot, projectDir, buildTarget, ngPackageConfig, tree);
472475

476+
const defaultSourceRoot = join(normalizedProjectRoot, 'src');
477+
if (
478+
project.sourceRoot === undefined ||
479+
normalizeRelativePath(project.sourceRoot) === defaultSourceRoot
480+
) {
481+
project.sourceRoot = project.root;
482+
}
483+
484+
if (normalizeRelativePath(project.sourceRoot) === normalizedProjectRoot) {
485+
updateLibraryTsConfigs(project, normalizedProjectRoot, buildTarget, tree);
486+
}
487+
473488
const packageJsonPath = join(normalizedProjectRoot, 'package.json');
474489

475490
// Delete primary ng-package.json if it exists
@@ -582,6 +597,104 @@ function updateLibraryPackageJson(
582597
json.modify(['exports'], updatedExports);
583598
}
584599

600+
/**
601+
* Updates `include` globs in the library's TypeScript configuration files (such as
602+
* `tsconfig.lib.json` and `tsconfig.spec.json`) from `src/**` to `**` so secondary
603+
* entry points outside `src/` are covered by TypeScript and test discovery.
604+
*
605+
* @param project The library project definition in `angular.json`.
606+
* @param normalizedProjectRoot The normalized root directory of the library project.
607+
* @param buildTarget The library's `build` target definition in `angular.json`.
608+
* @param tree The virtual file system tree.
609+
*/
610+
function updateLibraryTsConfigs(
611+
project: ProjectDefinition,
612+
normalizedProjectRoot: string,
613+
buildTarget: TargetDefinition,
614+
tree: Tree,
615+
): void {
616+
const tsConfigPaths = new Set<string>([
617+
join(normalizedProjectRoot, 'tsconfig.lib.json'),
618+
join(normalizedProjectRoot, 'tsconfig.spec.json'),
619+
]);
620+
621+
for (const targetName of ['build', 'test']) {
622+
const target = targetName === 'build' ? buildTarget : project.targets.get(targetName);
623+
if (!target) {
624+
continue;
625+
}
626+
627+
for (const [, options] of allTargetOptions(target, false)) {
628+
if (typeof options['tsConfig'] === 'string') {
629+
tsConfigPaths.add(normalizeRelativePath(options['tsConfig']));
630+
}
631+
}
632+
}
633+
634+
const outputPath =
635+
typeof buildTarget.options?.['outputPath'] === 'string'
636+
? normalizeRelativePath(buildTarget.options['outputPath'])
637+
: undefined;
638+
const relativeOutputPath =
639+
outputPath !== undefined ? relative(normalizedProjectRoot, outputPath) : undefined;
640+
const internalOutputDir =
641+
relativeOutputPath && !relativeOutputPath.startsWith('..') ? relativeOutputPath : undefined;
642+
643+
for (const tsConfigPath of tsConfigPaths) {
644+
if (
645+
!tree.exists(tsConfigPath) ||
646+
normalizeRelativePath(dirname(tsConfigPath)) !== normalizedProjectRoot
647+
) {
648+
continue;
649+
}
650+
651+
let json: JSONFile;
652+
try {
653+
json = new JSONFile(tree, tsConfigPath);
654+
} catch {
655+
continue;
656+
}
657+
658+
const include = json.get(['include']);
659+
if (!Array.isArray(include)) {
660+
continue;
661+
}
662+
663+
let updated = false;
664+
const newInclude: JsonValue[] = [];
665+
for (const entry of include) {
666+
if (typeof entry === 'string') {
667+
const replaced = entry.replace(/^(?:\.\/)?src\/(?=\*\*(?:\/|$))/, '');
668+
if (replaced !== entry) {
669+
updated = true;
670+
}
671+
if (!newInclude.includes(replaced)) {
672+
newInclude.push(replaced);
673+
}
674+
} else {
675+
newInclude.push(entry);
676+
}
677+
}
678+
679+
if (!updated) {
680+
continue;
681+
}
682+
683+
json.modify(['include'], newInclude);
684+
685+
if (internalOutputDir) {
686+
const exclude = json.get(['exclude']);
687+
if (Array.isArray(exclude)) {
688+
if (!exclude.includes(internalOutputDir)) {
689+
json.modify(['exclude'], [...exclude, internalOutputDir]);
690+
}
691+
} else if (exclude === undefined) {
692+
json.modify(['exclude'], [internalOutputDir]);
693+
}
694+
}
695+
}
696+
}
697+
585698
/**
586699
* Migration main entrypoint for use-library-builder.
587700
*/
@@ -605,7 +718,7 @@ export default function (): Rule {
605718
continue;
606719
}
607720

608-
if (updateLibraryTarget(project.root, buildTarget, tree, context)) {
721+
if (updateLibraryTarget(project, buildTarget, tree, context)) {
609722
hasMigratedLibrary = true;
610723
}
611724
}

‎packages/schematics/angular/migrations/use-library-builder/migration_spec.ts‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ describe('Migration to use the library builder', () => {
100100
} = newTree.readJson('/angular.json') as any;
101101

102102
const { builder, options, configurations } = lib.architect['build'];
103+
expect(lib.sourceRoot).toBe('projects/my-lib');
103104
expect(builder).toBe(Builders.BuildLibrary);
104105
expect(options.project).toBeUndefined();
105106
expect(options.entryPoints).toBeUndefined();
@@ -550,4 +551,118 @@ describe('Migration to use the library builder', () => {
550551
expect(rootPkg.devDependencies['ng-packagr']).toBeUndefined();
551552
expect(rootPkg.devDependencies['@angular/build']).toBeDefined();
552553
});
554+
555+
it('should align sourceRoot to root when sourceRoot is omitted', async () => {
556+
const angularJson = JSON.parse(tree.readContent('/angular.json'));
557+
delete angularJson.projects['my-lib'].sourceRoot;
558+
tree.overwrite('/angular.json', JSON.stringify(angularJson, undefined, 2));
559+
560+
const newTree = await schematicRunner.runSchematic(schematicName, {}, tree);
561+
const {
562+
projects: { 'my-lib': lib },
563+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
564+
} = newTree.readJson('/angular.json') as any;
565+
566+
expect(lib.sourceRoot).toBe('projects/my-lib');
567+
});
568+
569+
it('should preserve a custom sourceRoot when migrating', async () => {
570+
const angularJson = JSON.parse(tree.readContent('/angular.json'));
571+
angularJson.projects['my-lib'].sourceRoot = 'projects/my-lib/custom-src';
572+
tree.overwrite('/angular.json', JSON.stringify(angularJson, undefined, 2));
573+
574+
const newTree = await schematicRunner.runSchematic(schematicName, {}, tree);
575+
const {
576+
projects: { 'my-lib': lib },
577+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
578+
} = newTree.readJson('/angular.json') as any;
579+
580+
expect(lib.sourceRoot).toBe('projects/my-lib/custom-src');
581+
});
582+
583+
it('should update src/** include globs in tsconfig.lib.json and tsconfig.spec.json', async () => {
584+
tree.create(
585+
'/projects/my-lib/tsconfig.lib.json',
586+
JSON.stringify(
587+
{
588+
extends: '../../tsconfig.json',
589+
compilerOptions: {
590+
outDir: '../../out-tsc/lib',
591+
declaration: true,
592+
},
593+
include: ['src/**/*.ts'],
594+
exclude: ['**/*.spec.ts'],
595+
},
596+
undefined,
597+
2,
598+
),
599+
);
600+
tree.create(
601+
'/projects/my-lib/tsconfig.spec.json',
602+
JSON.stringify(
603+
{
604+
extends: '../../tsconfig.json',
605+
compilerOptions: {
606+
outDir: '../../out-tsc/spec',
607+
types: ['jasmine'],
608+
},
609+
include: ['src/**/*.d.ts', 'src/**/*.spec.ts', 'src/test-setup.ts'],
610+
},
611+
undefined,
612+
2,
613+
),
614+
);
615+
616+
const newTree = await schematicRunner.runSchematic(schematicName, {}, tree);
617+
618+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
619+
const tsConfigLib = newTree.readJson('/projects/my-lib/tsconfig.lib.json') as any;
620+
expect(tsConfigLib.include).toEqual(['**/*.ts']);
621+
expect(tsConfigLib.exclude).toEqual(['**/*.spec.ts']);
622+
623+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
624+
const tsConfigSpec = newTree.readJson('/projects/my-lib/tsconfig.spec.json') as any;
625+
expect(tsConfigSpec.include).toEqual(['**/*.d.ts', '**/*.spec.ts', 'src/test-setup.ts']);
626+
expect(tsConfigSpec.exclude).toBeUndefined();
627+
});
628+
629+
it('should exclude internal outputPath when broadening tsconfig include globs', async () => {
630+
tree.overwrite(
631+
'/projects/my-lib/ng-package.json',
632+
JSON.stringify({ lib: { entryFile: 'src/public-api.ts' } }),
633+
);
634+
tree.create(
635+
'/projects/my-lib/tsconfig.lib.json',
636+
JSON.stringify(
637+
{
638+
include: ['src/**/*.ts'],
639+
exclude: ['**/*.spec.ts'],
640+
},
641+
undefined,
642+
2,
643+
),
644+
);
645+
tree.create(
646+
'/projects/my-lib/tsconfig.spec.json',
647+
JSON.stringify(
648+
{
649+
include: ['src/**/*.d.ts', 'src/**/*.spec.ts'],
650+
},
651+
undefined,
652+
2,
653+
),
654+
);
655+
656+
const newTree = await schematicRunner.runSchematic(schematicName, {}, tree);
657+
658+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
659+
const tsConfigLib = newTree.readJson('/projects/my-lib/tsconfig.lib.json') as any;
660+
expect(tsConfigLib.include).toEqual(['**/*.ts']);
661+
expect(tsConfigLib.exclude).toEqual(['**/*.spec.ts', 'dist']);
662+
663+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
664+
const tsConfigSpec = newTree.readJson('/projects/my-lib/tsconfig.spec.json') as any;
665+
expect(tsConfigSpec.include).toEqual(['**/*.d.ts', '**/*.spec.ts']);
666+
expect(tsConfigSpec.exclude).toEqual(['dist']);
667+
});
553668
});

0 commit comments

Comments
 (0)