|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.io/license |
| 7 | + */ |
| 8 | + |
| 9 | +import Piscina from 'piscina'; |
| 10 | +import { ScriptTarget } from 'typescript'; |
| 11 | +import { maxWorkers } from '../../utils/environment-options'; |
| 12 | + |
| 13 | +/** |
| 14 | + * The maximum number of Workers that will be created to execute optimize tasks. |
| 15 | + */ |
| 16 | +const MAX_OPTIMIZE_WORKERS = maxWorkers; |
| 17 | + |
| 18 | +/** |
| 19 | + * The name of the plugin provided to Webpack when tapping Webpack compiler hooks. |
| 20 | + */ |
| 21 | +const PLUGIN_NAME = 'angular-javascript-optimizer'; |
| 22 | + |
| 23 | +/** |
| 24 | + * The options used to configure the {@link JavaScriptOptimizerPlugin}. |
| 25 | + */ |
| 26 | +export interface JavaScriptOptimizerOptions { |
| 27 | + /** |
| 28 | + * Enables advanced optimizations in the underlying JavaScript optimizers. |
| 29 | + * This currently increases the `terser` passes to 3 and enables the `pure_getters` |
| 30 | + * option for `terser`. |
| 31 | + */ |
| 32 | + advanced: boolean; |
| 33 | + |
| 34 | + /** |
| 35 | + * An object record of string keys that will be replaced with their respective values when found |
| 36 | + * within the code during optimization. |
| 37 | + */ |
| 38 | + define: Record<string, string | number | boolean>; |
| 39 | + |
| 40 | + /** |
| 41 | + * Enables the generation of a sourcemap during optimization. |
| 42 | + * The output sourcemap will be a full sourcemap containing the merge of the input sourcemap and |
| 43 | + * all intermediate sourcemaps. |
| 44 | + */ |
| 45 | + sourcemap: boolean; |
| 46 | + |
| 47 | + /** |
| 48 | + * The ECMAScript version that should be used when generating output code. |
| 49 | + * The optimizer will not adjust the output code with features present in newer |
| 50 | + * ECMAScript versions. |
| 51 | + */ |
| 52 | + target: ScriptTarget; |
| 53 | + |
| 54 | + /** |
| 55 | + * Enables the retention of identifier names and ensures that function and class names are |
| 56 | + * present in the output code. |
| 57 | + */ |
| 58 | + keepNames: boolean; |
| 59 | + |
| 60 | + /** |
| 61 | + * Enables the removal of all license comments from the output code. |
| 62 | + */ |
| 63 | + removeLicenses: boolean; |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * A Webpack plugin that provides JavaScript optimization capabilities. |
| 68 | + * |
| 69 | + * The plugin uses both `esbuild` and `terser` to provide both fast and highly-optimized |
| 70 | + * code output. `esbuild` is used as an initial pass to remove the majority of unused code |
| 71 | + * as well as shorten identifiers. `terser` is then used as a secondary pass to apply |
| 72 | + * optimizations not yet implemented by `esbuild`. |
| 73 | + */ |
| 74 | +export class JavaScriptOptimizerPlugin { |
| 75 | + constructor(public options: Partial<JavaScriptOptimizerOptions> = {}) {} |
| 76 | + |
| 77 | + apply(compiler: import('webpack').Compiler) { |
| 78 | + const { OriginalSource, SourceMapSource } = compiler.webpack.sources; |
| 79 | + |
| 80 | + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { |
| 81 | + compilation.hooks.processAssets.tapPromise( |
| 82 | + { |
| 83 | + name: PLUGIN_NAME, |
| 84 | + stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE, |
| 85 | + }, |
| 86 | + async (compilationAssets) => { |
| 87 | + const scriptsToOptimize = []; |
| 88 | + |
| 89 | + // Analyze the compilation assets for scripts that require optimization |
| 90 | + for (const assetName of Object.keys(compilationAssets)) { |
| 91 | + if (assetName.endsWith('.js')) { |
| 92 | + const scriptAsset = compilation.getAsset(assetName); |
| 93 | + if (scriptAsset && !scriptAsset.info.minimized) { |
| 94 | + const { source, map } = scriptAsset.source.sourceAndMap(); |
| 95 | + scriptsToOptimize.push({ |
| 96 | + name: scriptAsset.name, |
| 97 | + code: typeof source === 'string' ? source : source.toString(), |
| 98 | + map, |
| 99 | + }); |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + if (scriptsToOptimize.length === 0) { |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + // Ensure all replacement values are strings which is the expected type for esbuild |
| 109 | + let define: Record<string, string> | undefined; |
| 110 | + if (this.options.define) { |
| 111 | + define = {}; |
| 112 | + for (const [key, value] of Object.entries(this.options.define)) { |
| 113 | + define[key] = String(value); |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + let target = 2017; |
| 118 | + if (this.options.target) { |
| 119 | + if (this.options.target <= ScriptTarget.ES5) { |
| 120 | + target = 5; |
| 121 | + } else if (this.options.target < ScriptTarget.ESNext) { |
| 122 | + target = Number(ScriptTarget[this.options.target].slice(2)); |
| 123 | + } else { |
| 124 | + target = 2020; |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + // Setup the options used by all worker tasks |
| 129 | + const optimizeOptions = { |
| 130 | + sourcemap: this.options.sourcemap, |
| 131 | + define, |
| 132 | + keepNames: this.options.keepNames, |
| 133 | + target, |
| 134 | + removeLicenses: this.options.removeLicenses, |
| 135 | + advanced: this.options.advanced, |
| 136 | + }; |
| 137 | + |
| 138 | + // Sort scripts so larger scripts start first - worker pool uses a FIFO queue |
| 139 | + scriptsToOptimize.sort((a, b) => a.code.length - b.code.length); |
| 140 | + |
| 141 | + // Initialize the task worker pool |
| 142 | + const workerPath = require.resolve('./javascript-optimizer-worker'); |
| 143 | + const workerPool = new Piscina({ |
| 144 | + filename: workerPath, |
| 145 | + maxThreads: MAX_OPTIMIZE_WORKERS, |
| 146 | + }); |
| 147 | + |
| 148 | + // Enqueue script optimization tasks and update compilation assets as the tasks complete |
| 149 | + try { |
| 150 | + const tasks = []; |
| 151 | + for (const { name, code, map } of scriptsToOptimize) { |
| 152 | + tasks.push( |
| 153 | + workerPool |
| 154 | + .run({ |
| 155 | + asset: { |
| 156 | + name, |
| 157 | + code, |
| 158 | + map, |
| 159 | + }, |
| 160 | + options: optimizeOptions, |
| 161 | + }) |
| 162 | + .then( |
| 163 | + ({ code, name, map }) => { |
| 164 | + let optimizedAsset; |
| 165 | + if (map) { |
| 166 | + optimizedAsset = new SourceMapSource(code, name, map); |
| 167 | + } else { |
| 168 | + optimizedAsset = new OriginalSource(code, name); |
| 169 | + } |
| 170 | + compilation.updateAsset(name, optimizedAsset, { minimized: true }); |
| 171 | + }, |
| 172 | + (error) => { |
| 173 | + const optimizationError = new compiler.webpack.WebpackError( |
| 174 | + `Optimization error [${name}]: ${error.stack || error.message}`, |
| 175 | + ); |
| 176 | + compilation.errors.push(optimizationError); |
| 177 | + }, |
| 178 | + ), |
| 179 | + ); |
| 180 | + } |
| 181 | + |
| 182 | + await Promise.all(tasks); |
| 183 | + } finally { |
| 184 | + void workerPool.destroy(); |
| 185 | + } |
| 186 | + }, |
| 187 | + ); |
| 188 | + }); |
| 189 | + } |
| 190 | +} |
0 commit comments