Skip to content

Commit bd024c0

Browse files
committed
feat(compiler): lower @NgModule ids if needed (#23031)
This change allows the id of an NgModule to be dynamically computed if needed. PR Close #23031
1 parent 884bf0e commit bd024c0

File tree

4 files changed

+24
-6
lines changed

4 files changed

+24
-6
lines changed

packages/compiler-cli/src/transformers/program.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ const MAX_FILE_COUNT_FOR_SINGLE_FILE_EMIT = 20;
6868
/**
6969
* Fields to lower within metadata in render2 mode.
7070
*/
71-
const LOWER_FIELDS = ['useValue', 'useFactory', 'data'];
71+
const LOWER_FIELDS = ['useValue', 'useFactory', 'data', 'id'];
7272

7373
/**
7474
* Fields to lower within metadata in render3 mode.

packages/compiler-cli/test/ngc_spec.ts

+17
Original file line numberDiff line numberDiff line change
@@ -826,6 +826,23 @@ describe('ngc transformer command-line', () => {
826826
expect(mymoduleSource).not.toContain('ɵ0');
827827
});
828828

829+
it('should lower an NgModule id', () => {
830+
write('mymodule.ts', `
831+
import {NgModule} from '@angular/core';
832+
833+
@NgModule({
834+
id: (() => 'test')(),
835+
})
836+
export class MyModule {}
837+
`);
838+
expect(compile()).toEqual(0);
839+
840+
const mymodulejs = path.resolve(outDir, 'mymodule.js');
841+
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
842+
expect(mymoduleSource).toContain('id: ɵ0');
843+
expect(mymoduleSource).toMatch(/ɵ0 = .*'test'/);
844+
});
845+
829846
it('should be able to lower supported expressions', () => {
830847
writeConfig(`{
831848
"extends": "./tsconfig-base.json",

packages/compiler/src/aot/static_reflector.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const IGNORE = {
2828

2929
const USE_VALUE = 'useValue';
3030
const PROVIDE = 'provide';
31-
const REFERENCE_SET = new Set([USE_VALUE, 'useFactory', 'data']);
31+
const REFERENCE_SET = new Set([USE_VALUE, 'useFactory', 'data', 'id']);
3232
const TYPEGUARD_POSTFIX = 'TypeGuard';
3333
const USE_IF = 'UseIf';
3434

packages/compiler/src/ng_module_compiler.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,11 @@ export class NgModuleCompiler {
5555
]));
5656

5757
if (ngModuleMeta.id) {
58-
const registerFactoryStmt =
59-
o.importExpr(Identifiers.RegisterModuleFactoryFn)
60-
.callFn([o.literal(ngModuleMeta.id), o.variable(ngModuleFactoryVar)])
61-
.toStmt();
58+
const id = typeof ngModuleMeta.id === 'string' ? o.literal(ngModuleMeta.id) :
59+
ctx.importExpr(ngModuleMeta.id);
60+
const registerFactoryStmt = o.importExpr(Identifiers.RegisterModuleFactoryFn)
61+
.callFn([id, o.variable(ngModuleFactoryVar)])
62+
.toStmt();
6263
ctx.statements.push(registerFactoryStmt);
6364
}
6465

0 commit comments

Comments
 (0)