Skip to content

Commit c2adb58

Browse files
aminesbdevclaude
andcommitted
Support Angular 21
The `enableTemplateSourceLocations` compiler option only exists since Angular 22.1.4. Before that, the compiler has the same feature behind `setEnableTemplateSourceLocations()`, a function that `@angular/compiler` exports for Angular's own tests, and the runtime writes the same attribute. - New `ngx-source-inspector/enable-source-locations` entry point, a preload for `ng serve` that calls that function in the process and the worker thread that compile the templates: NODE_OPTIONS="--import ngx-source-inspector/enable-source-locations" ng serve It only does something for the dev server, so a production build stays clean even when NODE_OPTIONS is set for it too. - `ng add` looks at the installed Angular version: with the compiler option it does what it did before, without it it only adds the provider and prints the command above. - The peer dependencies accept Angular 21 and 22. CI sets up a new Angular 21 app with `ng add` and checks that `ng serve` with the preload produces source locations and that a production build doesn't. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent ab9e609 commit c2adb58

12 files changed

Lines changed: 430 additions & 54 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,5 @@ jobs:
1919
- run: npm test
2020
- name: Check that nothing ends up in production bundles
2121
run: npm run check:production
22+
- name: Check the package with Angular 21
23+
run: npm run check:angular-21

‎README.md‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ It only runs in development builds.
99

1010
> **Experimental.** This relies on `enableTemplateSourceLocations`, a compiler option that Angular
1111
> doesn't document and doesn't cover by semver. It could change or go away in any release. Tested
12-
> with Angular 22.2. This isn't an official Angular package. The proposal to support this in Angular
13-
> itself is [angular/angular#70927](https://github.com/angular/angular/issues/70927).
12+
> with Angular 21.2 and 22.2. This isn't an official Angular package. The proposal to support this
13+
> in Angular itself is [angular/angular#70927](https://github.com/angular/angular/issues/70927).
1414
1515
## Install
1616

@@ -58,6 +58,25 @@ Then run `ng serve`, hold Alt and move the mouse over the page.
5858
};
5959
```
6060

61+
### Angular 21
62+
63+
The compiler option exists since Angular 22.1.4. Before that, `ng add` only adds the provider (skip
64+
steps 1 and 2 of the manual setup), and a preload turns the source locations on when you start the
65+
dev server:
66+
67+
```sh
68+
NODE_OPTIONS="--import ngx-source-inspector/enable-source-locations" ng serve
69+
```
70+
71+
You can put that in the `start` script of your `package.json`. On Windows, set the variable with
72+
[cross-env](https://www.npmjs.com/package/cross-env).
73+
74+
The preload calls `setEnableTemplateSourceLocations()`, which `@angular/compiler` exports for
75+
Angular's own tests, in the process that compiles your templates. It only does something for the dev
76+
server (`ng serve`, or a `serve` target): `ng build` and the other commands ignore it.
77+
78+
Once you're on Angular 22.2 or later, remove it and run `ng add ngx-source-inspector` again.
79+
6180
## Options
6281

6382
```ts
@@ -92,6 +111,8 @@ for production:
92111
becomes an empty provider list and the inspector code is dropped from the bundle.
93112
- The template paths come from the compiler option. If you turn it on in `tsconfig.app.json`, every
94113
template path ships in your production bundle. That's why it goes in a development-only tsconfig.
114+
- In Angular 21, the preload only turns the source locations on for the dev server, so a production
115+
build stays clean even if `NODE_OPTIONS` is set for it too.
95116

96117
This repository's CI builds the demo app for production and fails if the bundle contains any
97118
inspector code, `data-ng-source-location` attribute or template path. To check your own app, build
@@ -129,6 +150,7 @@ npm run build:lib # library and ng-add schematic, in dist/ngx-source-ins
129150
npm start # demo app with the inspector
130151
npm test # unit tests and schematic tests
131152
npm run check:production # production build of the demo, checked for leftovers
153+
npm run check:angular-21 # ng add, ng serve and a production build in a new Angular 21 app
132154
```
133155

134156
The first prototype, linked from the Angular issue, is tagged

‎package.json‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@
77
"build": "npm run build:lib && ng build inspector-demo",
88
"build:lib": "ng build ngx-source-inspector && npm run build:schematics && node scripts/copy-package-files.mjs",
99
"build:schematics": "tsc -p projects/ngx-source-inspector/tsconfig.schematics.json && node scripts/copy-schematics-assets.mjs",
10-
"test": "ng test ngx-source-inspector --watch=false && npm run test:schematics",
10+
"test": "ng test ngx-source-inspector --watch=false && npm run test:schematics && npm run test:preload",
1111
"test:schematics": "tsc -p projects/ngx-source-inspector/tsconfig.schematics.spec.json && node --test out-tsc/schematics/ng-add/index.spec.js",
12-
"check:production": "ng build inspector-demo --configuration production && node scripts/check-production-bundle.mjs"
12+
"test:preload": "node --test projects/ngx-source-inspector/node/enable-source-locations.spec.mjs",
13+
"check:production": "ng build inspector-demo --configuration production && node scripts/check-production-bundle.mjs",
14+
"check:angular-21": "node scripts/check-angular-21.mjs"
1315
},
1416
"private": true,
1517
"packageManager": "npm@11.19.0",
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Turns on template source locations in Angular versions that don't have the
2+
// `enableTemplateSourceLocations` compiler option yet (before 22.1.4). Preload it into `ng serve`:
3+
//
4+
// NODE_OPTIONS="--import ngx-source-inspector/enable-source-locations" ng serve
5+
//
6+
// In those versions the only switch is `setEnableTemplateSourceLocations()`, a function that
7+
// `@angular/compiler` exports for Angular's own tests. It has to be called in the process, or the
8+
// worker thread, that compiles the templates, which is why this is a preload.
9+
import { createRequire } from 'node:module';
10+
import { join } from 'node:path';
11+
import { pathToFileURL } from 'node:url';
12+
import { isMainThread } from 'node:worker_threads';
13+
14+
// Set by the process that runs the dev server, read by its worker threads and child processes,
15+
// which don't get the command line.
16+
const SERVING = 'NGX_SOURCE_INSPECTOR_SERVING';
17+
18+
// `ng serve`, `ng s`, `ng dev`, `ng run app:serve`, `nx serve app`...
19+
const isServeCommand = (arg) => /^(serve|s|dev)$|(^|:)serve(:|$)/.test(arg);
20+
21+
// NODE_OPTIONS reaches every Node.js process started with it, `ng build` included. Template paths
22+
// must not end up in production bundles, so this only does something for the dev server.
23+
const startsDevServer = isMainThread && process.argv.slice(2).some(isServeCommand);
24+
const alreadyServing = process.env[SERVING] === '1';
25+
26+
if (startsDevServer || alreadyServing) {
27+
process.env[SERVING] = '1';
28+
const compiler = await importWorkspaceCompiler();
29+
if (typeof compiler?.setEnableTemplateSourceLocations === 'function') {
30+
compiler.setEnableTemplateSourceLocations(true);
31+
} else if (compiler && !alreadyServing) {
32+
console.warn(
33+
'[ngx-source-inspector] This version of Angular has the `enableTemplateSourceLocations` ' +
34+
'compiler option, the `enable-source-locations` preload does nothing. Remove it and run ' +
35+
'`ng add ngx-source-inspector` to turn the option on for development builds.',
36+
);
37+
}
38+
}
39+
40+
/** The copy of `@angular/compiler` that the CLI of the current workspace compiles with. */
41+
async function importWorkspaceCompiler() {
42+
try {
43+
const require = createRequire(join(process.cwd(), 'package.json'));
44+
return await import(pathToFileURL(require.resolve('@angular/compiler')).href);
45+
} catch {
46+
// Not in an Angular workspace: another process that inherited NODE_OPTIONS.
47+
return null;
48+
}
49+
}
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import assert from 'node:assert/strict';
2+
import { execFileSync } from 'node:child_process';
3+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
4+
import { tmpdir } from 'node:os';
5+
import { join } from 'node:path';
6+
import { after, before, describe, it } from 'node:test';
7+
import { fileURLToPath } from 'node:url';
8+
9+
const preload = fileURLToPath(new URL('./enable-source-locations.mjs', import.meta.url));
10+
11+
// Stands in for the CLI: prints whether source locations are on in the main thread and in a worker
12+
// thread, where the CLI compiles templates.
13+
const CLI = `
14+
import { Worker } from 'node:worker_threads';
15+
const { enabled } = await import('@angular/compiler');
16+
const worker = new Worker(new URL('./worker.mjs', import.meta.url));
17+
worker.once('message', (inWorker) => console.log(JSON.stringify({ main: enabled(), worker: inWorker })));
18+
`;
19+
const WORKER = `
20+
import { parentPort } from 'node:worker_threads';
21+
const { enabled } = await import('@angular/compiler');
22+
parentPort.postMessage(enabled());
23+
`;
24+
25+
const OLD_COMPILER = `
26+
let on = false;
27+
export const setEnableTemplateSourceLocations = (value) => (on = value);
28+
export const enabled = () => on;
29+
`;
30+
// Since 22.1.4 the setter is gone, replaced by the compiler option.
31+
const NEW_COMPILER = 'export const enabled = () => false;';
32+
33+
describe('enable-source-locations preload', () => {
34+
let workspace;
35+
36+
const useCompiler = (code) =>
37+
writeFileSync(join(workspace, 'node_modules/@angular/compiler/index.mjs'), code);
38+
39+
const ng = (...args) => {
40+
const { NGX_SOURCE_INSPECTOR_SERVING, ...env } = process.env;
41+
const output = execFileSync(process.execPath, ['--import', preload, 'ng.mjs', ...args], {
42+
cwd: workspace,
43+
env,
44+
encoding: 'utf8',
45+
stdio: ['ignore', 'pipe', 'pipe'],
46+
});
47+
return JSON.parse(output);
48+
};
49+
50+
before(() => {
51+
workspace = mkdtempSync(join(tmpdir(), 'ngx-source-inspector-'));
52+
mkdirSync(join(workspace, 'node_modules/@angular/compiler'), { recursive: true });
53+
writeFileSync(
54+
join(workspace, 'node_modules/@angular/compiler/package.json'),
55+
JSON.stringify({ name: '@angular/compiler', exports: { '.': { default: './index.mjs' } } }),
56+
);
57+
writeFileSync(join(workspace, 'package.json'), '{}');
58+
writeFileSync(join(workspace, 'ng.mjs'), CLI);
59+
writeFileSync(join(workspace, 'worker.mjs'), WORKER);
60+
});
61+
62+
after(() => rmSync(workspace, { recursive: true, force: true }));
63+
64+
it('turns source locations on for the dev server, worker threads included', () => {
65+
useCompiler(OLD_COMPILER);
66+
for (const args of [['serve'], ['s', '--port', '4201'], ['dev'], ['run', 'app:serve']]) {
67+
assert.deepEqual(ng(...args), { main: true, worker: true }, args.join(' '));
68+
}
69+
});
70+
71+
it('leaves every other command alone', () => {
72+
useCompiler(OLD_COMPILER);
73+
for (const args of [['build'], ['build', '--configuration', 'production'], ['test'], []]) {
74+
assert.deepEqual(ng(...args), { main: false, worker: false }, args.join(' '));
75+
}
76+
});
77+
78+
it('does nothing in Angular versions that have the compiler option', () => {
79+
useCompiler(NEW_COMPILER);
80+
assert.deepEqual(ng('serve'), { main: false, worker: false });
81+
});
82+
83+
it('does nothing outside of an Angular workspace', () => {
84+
const elsewhere = mkdtempSync(join(tmpdir(), 'ngx-source-inspector-'));
85+
try {
86+
writeFileSync(join(elsewhere, 'ng.mjs'), 'console.log("started")');
87+
const output = execFileSync(process.execPath, ['--import', preload, 'ng.mjs', 'serve'], {
88+
cwd: elsewhere,
89+
encoding: 'utf8',
90+
});
91+
assert.equal(output.trim(), 'started');
92+
} finally {
93+
rmSync(elsewhere, { recursive: true, force: true });
94+
}
95+
});
96+
});

‎projects/ngx-source-inspector/package.json‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "ngx-source-inspector",
3-
"version": "0.1.0",
3+
"version": "0.2.0",
44
"description": "Hold Alt, hover an element of your Angular app to see which template line it comes from, Alt+click to open it in your editor. Development only.",
55
"keywords": [
66
"angular",
@@ -21,12 +21,17 @@
2121
"url": "https://github.com/aminesbdev/angular-source-inspector/issues"
2222
},
2323
"peerDependencies": {
24-
"@angular/common": "^22.2.0",
25-
"@angular/core": "^22.2.0"
24+
"@angular/common": ">=21.0.0 <23.0.0",
25+
"@angular/core": ">=21.0.0 <23.0.0"
2626
},
2727
"dependencies": {
2828
"tslib": "^2.3.0"
2929
},
30+
"exports": {
31+
"./enable-source-locations": {
32+
"default": "./node/enable-source-locations.mjs"
33+
}
34+
},
3035
"schematics": "./schematics/collection.json",
3136
"sideEffects": false
3237
}

‎projects/ngx-source-inspector/schematics/ng-add/index.spec.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,4 +102,54 @@ describe('ng-add', () => {
102102
/no "development" build configuration/,
103103
);
104104
});
105+
106+
describe('before the compiler option exists', () => {
107+
const logs: string[] = [];
108+
runner.logger.subscribe((entry) => logs.push(entry.message));
109+
110+
beforeEach(() => {
111+
const packageJson = readJson(tree, 'package.json');
112+
packageJson.dependencies['@angular/core'] = '^21.2.0';
113+
tree.overwrite('package.json', JSON.stringify(packageJson, null, 2));
114+
logs.length = 0;
115+
});
116+
117+
it('leaves the build configuration alone and points to the preload', async () => {
118+
const angularJson = tree.readText('angular.json');
119+
120+
const result = await runner.runSchematic('ng-add', { project: 'app' }, tree);
121+
122+
assert.equal(result.readText('angular.json'), angularJson);
123+
assert.equal(result.exists('projects/app/tsconfig.dev.json'), false);
124+
assert.match(
125+
logs.join('\n'),
126+
/NODE_OPTIONS="--import ngx-source-inspector\/enable-source-locations" ng serve/,
127+
);
128+
});
129+
130+
it('adds provideSourceInspector() to the application providers', async () => {
131+
const result = await runner.runSchematic('ng-add', { project: 'app' }, tree);
132+
133+
assert.match(
134+
result.readText('projects/app/src/app/app.config.ts'),
135+
/provideSourceInspector\(\)/,
136+
);
137+
});
138+
139+
it('goes by the installed version rather than the one in package.json', async () => {
140+
tree.create('node_modules/@angular/core/package.json', '{"version": "22.1.4"}');
141+
142+
const result = await runner.runSchematic('ng-add', { project: 'app' }, tree);
143+
144+
assert.equal(result.exists('projects/app/tsconfig.dev.json'), true);
145+
});
146+
147+
it('still needs the preload in the 22 releases that came before the option', async () => {
148+
tree.create('node_modules/@angular/core/package.json', '{"version": "22.1.3"}');
149+
150+
const result = await runner.runSchematic('ng-add', { project: 'app' }, tree);
151+
152+
assert.equal(result.exists('projects/app/tsconfig.dev.json'), false);
153+
});
154+
});
105155
});

0 commit comments

Comments
 (0)