-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathscripts-webpack-plugin.ts
211 lines (176 loc) · 6.54 KB
/
scripts-webpack-plugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { interpolateName } from 'loader-utils';
import * as path from 'node:path';
import { Chunk, Compilation, Compiler, sources as webpackSources } from 'webpack';
import { assertIsError } from '../../../utils/error';
import { addError } from '../../../utils/webpack-diagnostics';
const Entrypoint = require('webpack/lib/Entrypoint');
/**
* The name of the plugin provided to Webpack when tapping Webpack compiler hooks.
*/
const PLUGIN_NAME = 'scripts-webpack-plugin';
export interface ScriptsWebpackPluginOptions {
name: string;
sourceMap?: boolean;
scripts: string[];
filename: string;
basePath: string;
}
interface ScriptOutput {
filename: string;
source: webpackSources.CachedSource;
}
function addDependencies(compilation: Compilation, scripts: string[]): void {
for (const script of scripts) {
compilation.fileDependencies.add(script);
}
}
export class ScriptsWebpackPlugin {
private _lastBuildTime?: number;
private _cachedOutput?: ScriptOutput;
constructor(private options: ScriptsWebpackPluginOptions) {}
async shouldSkip(compilation: Compilation, scripts: string[]): Promise<boolean> {
if (this._lastBuildTime == undefined) {
this._lastBuildTime = Date.now();
return false;
}
for (const script of scripts) {
const scriptTime = await new Promise<number | undefined>((resolve, reject) => {
compilation.fileSystemInfo.getFileTimestamp(script, (error, entry) => {
if (error) {
reject(error);
return;
}
resolve(entry && typeof entry !== 'string' ? entry.safeTime : undefined);
});
});
if (!scriptTime || scriptTime > this._lastBuildTime) {
this._lastBuildTime = Date.now();
return false;
}
}
return true;
}
private _insertOutput(
compilation: Compilation,
{ filename, source }: ScriptOutput,
cached = false,
) {
const chunk = new Chunk(this.options.name);
chunk.rendered = !cached;
chunk.id = this.options.name;
chunk.ids = [chunk.id];
chunk.files.add(filename);
const entrypoint = new Entrypoint(this.options.name);
entrypoint.pushChunk(chunk);
chunk.addGroup(entrypoint);
compilation.entrypoints.set(this.options.name, entrypoint);
compilation.chunks.add(chunk);
compilation.assets[filename] = source;
compilation.hooks.chunkAsset.call(chunk, filename);
}
apply(compiler: Compiler): void {
if (this.options.scripts.length === 0) {
return;
}
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
// Use the resolver from the compilation instead of compiler.
// Using the latter will causes a lot of `DescriptionFileUtils.loadDescriptionFile` calls.
// See: https://github.com/angular/angular-cli/issues/24634#issuecomment-1425782668
const resolver = compilation.resolverFactory.get('normal', {
preferRelative: true,
useSyncFileSystemCalls: true,
// Caching must be disabled because it causes the resolver to become async after a rebuild.
cache: false,
});
const scripts: string[] = [];
for (const script of this.options.scripts) {
try {
const resolvedPath = resolver.resolveSync({}, this.options.basePath, script);
if (resolvedPath) {
scripts.push(resolvedPath);
} else {
addError(compilation, `Cannot resolve '${script}'.`);
}
} catch (error) {
assertIsError(error);
addError(compilation, error.message);
}
}
compilation.hooks.additionalAssets.tapPromise(PLUGIN_NAME, async () => {
if (await this.shouldSkip(compilation, scripts)) {
if (this._cachedOutput) {
this._insertOutput(compilation, this._cachedOutput, true);
}
addDependencies(compilation, scripts);
return;
}
const sourceGetters = scripts.map((fullPath) => {
return new Promise<webpackSources.Source>((resolve, reject) => {
compilation.inputFileSystem.readFile(
fullPath,
(err?: Error | null, data?: string | Buffer) => {
if (err) {
reject(err);
return;
}
const content = data?.toString() ?? '';
let source;
if (this.options.sourceMap) {
// TODO: Look for source map file (for '.min' scripts, etc.)
let adjustedPath = fullPath;
if (this.options.basePath) {
adjustedPath = path.relative(this.options.basePath, fullPath);
}
source = new webpackSources.OriginalSource(content, adjustedPath);
} else {
source = new webpackSources.RawSource(content);
}
resolve(source);
},
);
});
});
const sources = await Promise.all(sourceGetters);
const concatSource = new webpackSources.ConcatSource();
sources.forEach((source) => {
concatSource.add(source);
concatSource.add('\n;');
});
const combinedSource = new webpackSources.CachedSource(concatSource);
const output = { filename: this.options.filename, source: combinedSource };
this._insertOutput(compilation, output);
this._cachedOutput = output;
addDependencies(compilation, scripts);
});
compilation.hooks.processAssets.tapPromise(
{
name: PLUGIN_NAME,
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
},
async () => {
const assetName = this.options.filename;
const asset = compilation.getAsset(assetName);
if (asset) {
const interpolatedFilename = interpolateName(
// TODO: Revisit. Previously due to lack of type safety, this object
// was fine, but in practice it doesn't match the type of the loader context.
{ resourcePath: 'scripts.js' } as Parameters<typeof interpolateName>[0],
assetName,
{ content: asset.source.source() },
);
if (assetName !== interpolatedFilename) {
compilation.renameAsset(assetName, interpolatedFilename);
}
}
},
);
});
}
}