Skip to content

Commit 76faae5

Browse files
jelbournkara
authored andcommitted
chore: add @__PURE__ annotation to ES5 output for uglify (#4147)
1 parent 380b390 commit 76faae5

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

tools/gulp/util/annotate-pure.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
const iifeExpression =
3+
new RegExp('^(var (\\S+) = )(\\(function \\(\\) \\{\\n(?: ' +
4+
'(?:\\/\\*\\*| \\*|\\*\\/|\\/\\/)[^\\n]*\\n)* function \\2\\([^\\)]*\\) \\{\\n)', 'mg');
5+
6+
/**
7+
* Adds `@__PURE__` annotation comments to IIFEs containing ES5-downleveled classes generated by
8+
* TypeScript so that Uglify can tree-shake classes that are not referenced.
9+
*
10+
* @param fileContent The content of the file for which `@__PURE__` will be added.
11+
* @returns The content of the file with `@__PURE__` annotations added.
12+
*/
13+
export function addPureAnnotations(fileContent: string) {
14+
return fileContent
15+
// Prefix downleveled classes w/ the @__PURE__ annotation.
16+
.replace(iifeExpression, '$1/*@__PURE__*/$3')
17+
// Prefix downleveled classes that extend another class w/ the @__PURE__ annotation
18+
.replace(
19+
/^(var (\S+) = )(\(function \(_super\) \{\n __extends\(\2, _super\);\n)/mg,
20+
'$1/*@__PURE__*/$3'
21+
);
22+
}

tools/gulp/util/package-build.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import {
1111
DIST_BUNDLES, DIST_ROOT, SOURCE_ROOT, PROJECT_ROOT, LICENSE_BANNER, MATERIAL_VERSION
1212
} from '../constants';
13+
import {addPureAnnotations} from './annotate-pure';
1314

1415
// There are no type definitions available for these imports.
1516
const uglify = require('uglify-js');
@@ -38,6 +39,7 @@ export function composeRelease(packageName: string) {
3839
updatePackageVersion(releasePath);
3940
createTypingFile(releasePath, packageName);
4041
createMetadataFile(releasePath, packageName);
42+
addPureAnnotationCommentsToEs5Bundle(releasePath, packageName);
4143
}
4244

4345
/** Builds the bundles for the specified package. */
@@ -156,3 +158,12 @@ function inlinePackageMetadataFiles(packagePath: string) {
156158
writeFileSync(path , JSON.stringify(metadata), 'utf-8');
157159
});
158160
}
161+
162+
/** Adds Uglify "@__PURE__" decorations to the generated ES5 bundle. */
163+
function addPureAnnotationCommentsToEs5Bundle(outputDir: string, entryName: string) {
164+
const es5BundlePath = join(outputDir, '@angular', `${entryName}.es5.js`);
165+
const originalContent = readFileSync(es5BundlePath, 'utf-8');
166+
const annotatedContent = addPureAnnotations(originalContent);
167+
168+
writeFileSync(es5BundlePath, annotatedContent, 'utf-8');
169+
}

0 commit comments

Comments
 (0)