Skip to content

Commit fe84683

Browse files
author
David Neil
committed
fix(ngcc): use annotateForClosureCompiler option
Adds @nocollapse to static properties added by ngcc iff annotateForClosureCompiler is true. The Closure Compiler will collapse static properties into the global namespace. Adding this annotation keeps the properties attached to their respective object, which allows them to be referenced via a class's constructor. The annotation is already added by ngtsc and ngc under the same option, this commit extends the functionality to ngcc. Closes angular#36618.
1 parent cb13731 commit fe84683

5 files changed

Lines changed: 53 additions & 17 deletions

File tree

‎packages/compiler-cli/ngcc/src/analysis/decoration_analyzer.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,13 +99,13 @@ export class DecorationAnalyzer {
9999
/* i18nUseExternalIds */ true, this.bundle.enableI18nLegacyMessageIdFormat,
100100
/* i18nNormalizeLineEndingsInICUs */ false, this.moduleResolver, this.cycleAnalyzer,
101101
this.refEmitter, NOOP_DEFAULT_IMPORT_RECORDER, NOOP_DEPENDENCY_TRACKER,
102-
this.injectableRegistry, /* annotateForClosureCompiler */ false),
102+
this.injectableRegistry, !!this.compilerOptions.annotateForClosureCompiler),
103103
// See the note in ngtsc about why this cast is needed.
104104
// clang-format off
105105
new DirectiveDecoratorHandler(
106106
this.reflectionHost, this.evaluator, this.fullRegistry, this.scopeRegistry,
107107
this.fullMetaReader, NOOP_DEFAULT_IMPORT_RECORDER, this.injectableRegistry, this.isCore,
108-
/* annotateForClosureCompiler */ false,
108+
!!this.compilerOptions.annotateForClosureCompiler,
109109
// In ngcc we want to compile undecorated classes with Angular features. As of
110110
// version 10, undecorated classes that use Angular features are no longer handled
111111
// in ngtsc, but we want to ensure compatibility in ngcc for outdated libraries that
@@ -126,7 +126,7 @@ export class DecorationAnalyzer {
126126
this.scopeRegistry, this.referencesRegistry, this.isCore, /* routeAnalyzer */ null,
127127
this.refEmitter,
128128
/* factoryTracker */ null, NOOP_DEFAULT_IMPORT_RECORDER,
129-
/* annotateForClosureCompiler */ false, this.injectableRegistry),
129+
!!this.compilerOptions.annotateForClosureCompiler, this.injectableRegistry),
130130
];
131131
compiler = new NgccTraitCompiler(this.handlers, this.reflectionHost);
132132
migrations: Migration[] = [

‎packages/compiler-cli/ngcc/src/packages/transformer.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,8 @@ export class Transformer {
9494
// Transform the source files and source maps.
9595
const srcFormatter = this.getRenderingFormatter(ngccReflectionHost, bundle);
9696

97-
const renderer = new Renderer(reflectionHost, srcFormatter, this.fs, this.logger, bundle);
97+
const renderer =
98+
new Renderer(reflectionHost, srcFormatter, this.fs, this.logger, bundle, this.tsConfig);
9899
let renderedFiles = renderer.renderProgram(
99100
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
100101

‎packages/compiler-cli/ngcc/src/rendering/renderer.ts‎

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@
55
* Use of this source code is governed by an MIT-style license that can be
66
* found in the LICENSE file at https://angular.io/license
77
*/
8-
import {ConstantPool, Expression, Statement, WrappedNodeExpr, WritePropExpr} from '@angular/compiler';
8+
import {CommentStmt, ConstantPool, Expression, Statement, WrappedNodeExpr, WritePropExpr} from '@angular/compiler';
99
import MagicString from 'magic-string';
1010
import * as ts from 'typescript';
1111

1212
import {FileSystem} from '../../../src/ngtsc/file_system';
1313
import {ImportManager} from '../../../src/ngtsc/translator';
14+
import {ParsedConfiguration} from '../../../src/perform_compile';
1415
import {PrivateDeclarationsAnalyses} from '../analysis/private_declarations_analyzer';
1516
import {SwitchMarkerAnalyses, SwitchMarkerAnalysis} from '../analysis/switch_marker_analyzer';
1617
import {CompiledClass, CompiledFile, DecorationAnalyses} from '../analysis/types';
@@ -32,7 +33,8 @@ import {FileToWrite, getImportRewriter, stripExtension} from './utils';
3233
export class Renderer {
3334
constructor(
3435
private host: NgccReflectionHost, private srcFormatter: RenderingFormatter,
35-
private fs: FileSystem, private logger: Logger, private bundle: EntryPointBundle) {}
36+
private fs: FileSystem, private logger: Logger, private bundle: EntryPointBundle,
37+
private tsConfig: ParsedConfiguration|null = null) {}
3638

3739
renderProgram(
3840
decorationAnalyses: DecorationAnalyses, switchMarkerAnalyses: SwitchMarkerAnalyses,
@@ -82,8 +84,9 @@ export class Renderer {
8284
this.srcFormatter.removeDecorators(outputText, decoratorsToRemove);
8385

8486
compiledFile.compiledClasses.forEach(clazz => {
85-
const renderedDefinition =
86-
this.renderDefinitions(compiledFile.sourceFile, clazz, importManager);
87+
const renderedDefinition = this.renderDefinitions(
88+
compiledFile.sourceFile, clazz, importManager,
89+
!!this.tsConfig?.options.annotateForClosureCompiler);
8790
this.srcFormatter.addDefinitions(outputText, clazz, renderedDefinition);
8891

8992
const renderedStatements =
@@ -160,12 +163,14 @@ export class Renderer {
160163
* @param imports An object that tracks the imports that are needed by the rendered definitions.
161164
*/
162165
private renderDefinitions(
163-
sourceFile: ts.SourceFile, compiledClass: CompiledClass, imports: ImportManager): string {
166+
sourceFile: ts.SourceFile, compiledClass: CompiledClass, imports: ImportManager,
167+
annotateForClosureCompiler: boolean): string {
164168
const name = this.host.getInternalNameOfClass(compiledClass.declaration);
165-
const statements: Statement[] = compiledClass.compilation.map(c => {
166-
return createAssignmentStatement(name, c.name, c.initializer);
169+
const statements: Statement[][] = compiledClass.compilation.map(c => {
170+
return createAssignmentStatements(
171+
name, c.name, c.initializer, annotateForClosureCompiler ? '* @nocollapse ' : undefined);
167172
});
168-
return this.renderStatements(sourceFile, statements, imports);
173+
return this.renderStatements(sourceFile, Array.prototype.concat.apply([], statements), imports);
169174
}
170175

171176
/**
@@ -208,8 +213,16 @@ export function renderConstantPool(
208213
* compiled decorator to be applied to the class.
209214
* @param analyzedClass The info about the class whose statement we want to create.
210215
*/
211-
function createAssignmentStatement(
212-
receiverName: ts.DeclarationName, propName: string, initializer: Expression): Statement {
216+
function createAssignmentStatements(
217+
receiverName: ts.DeclarationName, propName: string, initializer: Expression,
218+
leadingComment?: string): Statement[] {
213219
const receiver = new WrappedNodeExpr(receiverName);
214-
return new WritePropExpr(receiver, propName, initializer).toStmt();
220+
const statements =
221+
[new WritePropExpr(
222+
receiver, propName, initializer, /* type */ undefined, /* sourceSpan */ undefined)
223+
.toStmt()];
224+
if (leadingComment !== undefined) {
225+
statements.unshift(new CommentStmt(leadingComment, true));
226+
}
227+
return statements;
215228
}

‎packages/compiler-cli/ngcc/test/integration/ngcc_spec.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1541,6 +1541,22 @@ runInEachFileSystem(() => {
15411541
});
15421542
});
15431543

1544+
describe('with Closure Compiler', () => {
1545+
it('should give closure annotated output with annotateForClosureCompiler: true', () => {
1546+
fs.writeFile(
1547+
_('/tsconfig.json'),
1548+
JSON.stringify({angularCompilerOptions: {annotateForClosureCompiler: true}}));
1549+
mainNgcc({basePath: '/dist', propertiesToConsider: ['es2015']});
1550+
const jsContents = fs.readFile(_(`/dist/local-package/index.js`));
1551+
expect(jsContents).toContain('/** @nocollapse */ \nAppComponent.ɵcmp =');
1552+
});
1553+
it('should default to not give closure annotated output', () => {
1554+
mainNgcc({basePath: '/dist', propertiesToConsider: ['es2015']});
1555+
const jsContents = fs.readFile(_(`/dist/local-package/index.js`));
1556+
expect(jsContents).not.toContain('/** @nocollapse */');
1557+
});
1558+
});
1559+
15441560
describe('with configuration files', () => {
15451561
it('should process a configured deep-import as an entry-point', () => {
15461562
loadTestFiles([

‎packages/compiler-cli/src/ngtsc/translator/src/translator.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -187,8 +187,14 @@ class ExpressionTranslatorVisitor implements ExpressionVisitor, StatementVisitor
187187
return ts.createThrow(stmt.error.visitExpression(this, context.withExpressionMode));
188188
}
189189

190-
visitCommentStmt(stmt: CommentStmt, context: Context): never {
191-
throw new Error('Method not implemented.');
190+
visitCommentStmt(stmt: CommentStmt, context: Context): ts.NotEmittedStatement {
191+
const commentStmt = ts.createNotEmittedStatement(ts.createLiteral(''));
192+
ts.addSyntheticLeadingComment(
193+
commentStmt,
194+
stmt.multiline ? ts.SyntaxKind.MultiLineCommentTrivia :
195+
ts.SyntaxKind.SingleLineCommentTrivia,
196+
stmt.comment, /** hasTrailingNewLine */ false);
197+
return commentStmt;
192198
}
193199

194200
visitJSDocCommentStmt(stmt: JSDocCommentStmt, context: Context): ts.NotEmittedStatement {

0 commit comments

Comments
 (0)