Skip to content

Commit

Permalink
feat(compiler): lower @NgModule ids if needed (#23031)
Browse files Browse the repository at this point in the history
This change allows the id of an NgModule to be dynamically computed if
needed.

PR Close #23031
  • Loading branch information
alxhub committed Mar 28, 2018
1 parent 884bf0e commit bd024c0
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 6 deletions.
2 changes: 1 addition & 1 deletion packages/compiler-cli/src/transformers/program.ts
Expand Up @@ -68,7 +68,7 @@ const MAX_FILE_COUNT_FOR_SINGLE_FILE_EMIT = 20;
/**
* Fields to lower within metadata in render2 mode.
*/
const LOWER_FIELDS = ['useValue', 'useFactory', 'data'];
const LOWER_FIELDS = ['useValue', 'useFactory', 'data', 'id'];

/**
* Fields to lower within metadata in render3 mode.
Expand Down
17 changes: 17 additions & 0 deletions packages/compiler-cli/test/ngc_spec.ts
Expand Up @@ -826,6 +826,23 @@ describe('ngc transformer command-line', () => {
expect(mymoduleSource).not.toContain('ɵ0');
});

it('should lower an NgModule id', () => {
write('mymodule.ts', `
import {NgModule} from '@angular/core';
@NgModule({
id: (() => 'test')(),
})
export class MyModule {}
`);
expect(compile()).toEqual(0);

const mymodulejs = path.resolve(outDir, 'mymodule.js');
const mymoduleSource = fs.readFileSync(mymodulejs, 'utf8');
expect(mymoduleSource).toContain('id: ɵ0');
expect(mymoduleSource).toMatch(/ɵ0 = .*'test'/);
});

it('should be able to lower supported expressions', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler/src/aot/static_reflector.ts
Expand Up @@ -28,7 +28,7 @@ const IGNORE = {

const USE_VALUE = 'useValue';
const PROVIDE = 'provide';
const REFERENCE_SET = new Set([USE_VALUE, 'useFactory', 'data']);
const REFERENCE_SET = new Set([USE_VALUE, 'useFactory', 'data', 'id']);
const TYPEGUARD_POSTFIX = 'TypeGuard';
const USE_IF = 'UseIf';

Expand Down
9 changes: 5 additions & 4 deletions packages/compiler/src/ng_module_compiler.ts
Expand Up @@ -55,10 +55,11 @@ export class NgModuleCompiler {
]));

if (ngModuleMeta.id) {
const registerFactoryStmt =
o.importExpr(Identifiers.RegisterModuleFactoryFn)
.callFn([o.literal(ngModuleMeta.id), o.variable(ngModuleFactoryVar)])
.toStmt();
const id = typeof ngModuleMeta.id === 'string' ? o.literal(ngModuleMeta.id) :
ctx.importExpr(ngModuleMeta.id);
const registerFactoryStmt = o.importExpr(Identifiers.RegisterModuleFactoryFn)
.callFn([id, o.variable(ngModuleFactoryVar)])
.toStmt();
ctx.statements.push(registerFactoryStmt);
}

Expand Down

0 comments on commit bd024c0

Please sign in to comment.