-
Notifications
You must be signed in to change notification settings - Fork 135
/
clean-webpack-plugin.ts
329 lines (277 loc) · 9.82 KB
/
clean-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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import { sync as delSync } from 'del';
import path from 'path';
import { Compilation, Compiler, Stats } from 'webpack';
export interface Options {
/**
* Simulate the removal of files
*
* default: false
*/
dry?: boolean;
/**
* Write Logs to Console
* (Always enabled when dry is true)
*
* default: false
*/
verbose?: boolean;
/**
* Automatically remove all unused webpack assets on rebuild
*
* default: true
*/
cleanStaleWebpackAssets?: boolean;
/**
* Do not allow removal of current webpack assets
*
* default: true
*/
protectWebpackAssets?: boolean;
/**
* Removes files once prior to Webpack compilation
* Not included in rebuilds (watch mode)
*
* Use !negative patterns to exclude files
*
* default: ['**\/*']
*/
cleanOnceBeforeBuildPatterns?: string[];
/**
* Removes files after every build (including watch mode) that match this pattern.
* Used for files that are not created directly by Webpack.
*
* Use !negative patterns to exclude files
*
* default: []
*/
cleanAfterEveryBuildPatterns?: string[];
/**
* Allow clean patterns outside of process.cwd()
*
* requires dry option to be explicitly set
*
* default: false
*/
dangerouslyAllowCleanPatternsOutsideProject?: boolean;
}
// Copied from https://github.com/sindresorhus/is-plain-obj/blob/97480673cf12145b32ec2ee924980d66572e8a86/index.js
function isPlainObject(value: unknown): boolean {
if (Object.prototype.toString.call(value) !== '[object Object]') {
return false;
}
const prototype = Object.getPrototypeOf(value);
return prototype === null || prototype === Object.getPrototypeOf({});
}
class CleanWebpackPlugin {
private readonly dry: boolean;
private readonly verbose: boolean;
private readonly cleanStaleWebpackAssets: boolean;
private readonly protectWebpackAssets: boolean;
private readonly cleanAfterEveryBuildPatterns: string[];
private readonly cleanOnceBeforeBuildPatterns: string[];
private readonly dangerouslyAllowCleanPatternsOutsideProject: boolean;
private currentAssets: string[];
private initialClean: boolean;
private outputPath: string;
constructor(options: Options = {}) {
if (isPlainObject(options) === false) {
throw new Error(`clean-webpack-plugin only accepts an options object. See:
https://github.com/johnagan/clean-webpack-plugin#options-and-defaults-optional`);
}
// @ts-ignore
if (options.allowExternal) {
throw new Error(
'clean-webpack-plugin: `allowExternal` option no longer supported. Use `dangerouslyAllowCleanPatternsOutsideProject`',
);
}
if (
options.dangerouslyAllowCleanPatternsOutsideProject === true &&
options.dry !== true &&
options.dry !== false
) {
// eslint-disable-next-line no-console
console.warn(
'clean-webpack-plugin: dangerouslyAllowCleanPatternsOutsideProject requires dry: false to be explicitly set. Enabling dry mode',
);
}
this.dangerouslyAllowCleanPatternsOutsideProject =
options.dangerouslyAllowCleanPatternsOutsideProject === true ||
false;
this.dry =
options.dry === true || options.dry === false
? options.dry
: this.dangerouslyAllowCleanPatternsOutsideProject === true ||
false;
this.verbose = this.dry === true || options.verbose === true || false;
this.cleanStaleWebpackAssets =
options.cleanStaleWebpackAssets === true ||
options.cleanStaleWebpackAssets === false
? options.cleanStaleWebpackAssets
: true;
this.protectWebpackAssets =
options.protectWebpackAssets === true ||
options.protectWebpackAssets === false
? options.protectWebpackAssets
: true;
this.cleanAfterEveryBuildPatterns = Array.isArray(
options.cleanAfterEveryBuildPatterns,
)
? options.cleanAfterEveryBuildPatterns
: [];
this.cleanOnceBeforeBuildPatterns = Array.isArray(
options.cleanOnceBeforeBuildPatterns,
)
? options.cleanOnceBeforeBuildPatterns
: ['**/*'];
/**
* Store webpack build assets
*/
this.currentAssets = [];
/**
* Only used with cleanOnceBeforeBuildPatterns
*/
this.initialClean = false;
this.outputPath = '';
this.apply = this.apply.bind(this);
this.handleInitial = this.handleInitial.bind(this);
this.handleDone = this.handleDone.bind(this);
this.removeFiles = this.removeFiles.bind(this);
}
apply(compiler: Compiler) {
if (!compiler.options.output || !compiler.options.output.path) {
// eslint-disable-next-line no-console
console.warn(
'clean-webpack-plugin: options.output.path not defined. Plugin disabled...',
);
return;
}
this.outputPath = compiler.options.output.path;
/**
* webpack 4+ comes with a new plugin system.
*
* Check for hooks in-order to support old plugin system
* webpack 5+ removed the old system, the check now breaks
*/
const hooks = compiler.hooks;
if (this.cleanOnceBeforeBuildPatterns.length !== 0) {
hooks.emit.tap('clean-webpack-plugin', (compilation) => {
this.handleInitial(compilation);
});
}
hooks.done.tap('clean-webpack-plugin', (stats) => {
this.handleDone(stats);
});
}
/**
* Initially remove files from output directory prior to build.
*
* Only happens once.
*
* Warning: It is recommended to initially clean your build directory outside of webpack to minimize unexpected behavior.
*/
handleInitial(compilation: Compilation) {
if (this.initialClean) {
return;
}
/**
* Do not remove files if there are compilation errors
*
* Handle logging inside this.handleDone
*/
const stats = compilation.getStats();
if (stats.hasErrors()) {
return;
}
this.initialClean = true;
this.removeFiles(this.cleanOnceBeforeBuildPatterns);
}
handleDone(stats: Stats) {
/**
* Do nothing if there is a webpack error
*/
if (stats.hasErrors()) {
if (this.verbose) {
// eslint-disable-next-line no-console
console.warn(
'clean-webpack-plugin: pausing due to webpack errors',
);
}
return;
}
/**
* Fetch Webpack's output asset files
*/
const assetList = Object.keys(stats.compilation.assets);
/**
* Get all files that were in the previous build but not the current
*
* (relies on del's cwd: outputPath option)
*/
const staleFiles = this.currentAssets.filter((previousAsset) => {
const assetCurrent = assetList.includes(previousAsset) === false;
return assetCurrent;
});
/**
* Save assets for next compilation
*/
this.currentAssets = assetList.sort();
const removePatterns = [];
/**
* Remove unused webpack assets
*/
if (this.cleanStaleWebpackAssets === true && staleFiles.length !== 0) {
removePatterns.push(...staleFiles);
}
/**
* Remove cleanAfterEveryBuildPatterns
*/
if (this.cleanAfterEveryBuildPatterns.length !== 0) {
removePatterns.push(...this.cleanAfterEveryBuildPatterns);
}
if (removePatterns.length !== 0) {
this.removeFiles(removePatterns);
}
}
removeFiles(patterns: string[]) {
try {
const deleted = delSync(patterns, {
force: this.dangerouslyAllowCleanPatternsOutsideProject,
// Change context to build directory
cwd: this.outputPath,
dryRun: this.dry,
dot: true,
ignore: this.protectWebpackAssets ? this.currentAssets : [],
});
/**
* Log if verbose is enabled
*/
if (this.verbose) {
deleted.forEach((file) => {
const filename = path.relative(process.cwd(), file);
const message = this.dry ? 'dry' : 'removed';
/**
* Use console.warn over .log
* https://github.com/webpack/webpack/issues/1904
* https://github.com/johnagan/clean-webpack-plugin/issues/11
*/
// eslint-disable-next-line no-console
console.warn(
`clean-webpack-plugin: ${message} ${filename}`,
);
});
}
} catch (error) {
const needsForce = /Cannot delete files\/folders outside the current working directory\./.test(
error.message,
);
if (needsForce) {
const message =
'clean-webpack-plugin: Cannot delete files/folders outside the current working directory. Can be overridden with the `dangerouslyAllowCleanPatternsOutsideProject` option.';
throw new Error(message);
}
/* istanbul ignore next */
throw error;
}
}
}
export { CleanWebpackPlugin };