-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathminify-plugin.ts
207 lines (183 loc) · 5 KB
/
minify-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
import {transform as defaultEsbuildTransform} from 'esbuild';
import {RawSource, SourceMapSource} from 'webpack-sources';
import webpack from 'webpack';
import {matchObject} from 'webpack/lib/ModuleFilenameHelpers';
import {MinifyPluginOptions} from './interfaces';
type Asset = webpack.compilation.Asset;
type KnownStatsPrinterContext = {
formatFlag(flag: string): string;
green(string: string): string;
};
type Tappable = {
tap(
name: string,
callback: (
minimized: boolean,
statsPrinterContext: KnownStatsPrinterContext,
) => void,
): void;
};
type StatsPrinter = {
hooks: {
print: {
for(name: string): Tappable;
};
};
};
// eslint-disable-next-line @typescript-eslint/no-var-requires
const {version} = require('../package');
const isJsFile = /\.[cm]?js(\?.*)?$/i;
const isCssFile = /\.css(\?.*)?$/i;
const pluginName = 'esbuild-minify';
const flatMap = <T, U>(
array: T[],
callback: (value: T) => U[],
): U[] => (
// eslint-disable-next-line unicorn/no-array-callback-reference
Array.prototype.concat(...array.map(callback))
);
class ESBuildMinifyPlugin {
private readonly options: MinifyPluginOptions;
constructor(options?: MinifyPluginOptions) {
this.options = {...options};
const hasMinify = Object.keys(this.options).some(k =>
k.startsWith('minify'),
);
if (!hasMinify) {
this.options.minify = true;
}
}
apply(compiler: webpack.Compiler): void {
compiler.hooks.compilation.tap(pluginName, compilation => {
const meta = JSON.stringify({
name: 'esbuild-loader',
version,
options: this.options,
});
compilation.hooks.chunkHash.tap(pluginName, (_, hash) => hash.update(meta));
type Wp5Compilation = typeof compilation & {
hooks: typeof compilation.hooks & {
processAssets: typeof compilation.hooks.optimizeAssets;
statsPrinter: typeof compilation.hooks.childCompiler; // Could be any SyncHook
};
constructor: {
PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE: number;
};
};
if ('processAssets' in compilation.hooks) {
const wp5Compilation = compilation as Wp5Compilation;
wp5Compilation.hooks.processAssets.tapPromise(
{
name: pluginName,
stage: wp5Compilation.constructor.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
// @ts-expect-error
additionalAssets: true,
},
async (assets: Asset[]) => this.transformAssets(compilation, Object.keys(assets)),
);
wp5Compilation.hooks.statsPrinter.tap(pluginName, (statsPrinter: StatsPrinter) => {
statsPrinter.hooks.print
.for('asset.info.minimized')
.tap(
pluginName,
(minimized, {green, formatFlag}: any) => (
minimized ?
green(formatFlag('minimized')) :
undefined
),
);
});
} else {
compilation.hooks.optimizeChunkAssets.tapPromise(
pluginName,
async chunks => this.transformAssets(
compilation,
flatMap(chunks, chunk => chunk.files),
),
);
}
});
}
async transformAssets(
compilation: webpack.compilation.Compilation,
assetNames: string[],
): Promise<void> {
const {options: {devtool}} = compilation.compiler;
const sourcemap = (
// TODO: drop support for esbuild sourcemap in future so it all goes through WP API
this.options.sourcemap === undefined ?
devtool && (devtool as string).includes('source-map') :
this.options.sourcemap
);
const {
css: minifyCss,
include,
exclude,
implementation,
...transformOptions
} = this.options;
if (implementation && typeof implementation.transform !== 'function') {
throw new TypeError(
`ESBuildMinifyPlugin: implementation.transform must be an ESBuild transform function. Received ${typeof implementation.transform}`,
);
}
const transforms = assetNames
.filter(assetName => (
(
isJsFile.test(assetName) ||
(
minifyCss &&
isCssFile.test(assetName)
)
) &&
matchObject({include, exclude}, assetName)),
)
.map((assetName): [string, Asset] => [
assetName,
compilation.getAsset(assetName),
])
.map(async ([
assetName,
{info, source: assetSource},
]) => {
const assetIsCss = isCssFile.test(assetName);
const {source, map} = assetSource.sourceAndMap();
const transform = implementation?.transform ?? defaultEsbuildTransform;
const result = await transform(source.toString(), {
...transformOptions,
loader: (
assetIsCss ?
'css' :
transformOptions.loader
),
sourcemap,
sourcefile: assetName,
});
compilation.updateAsset(
assetName,
(
sourcemap &&
// CSS source-maps not supported yet https://github.com/evanw/esbuild/issues/519
!assetIsCss
) ?
new SourceMapSource(
result.code || '',
assetName,
result.map as any,
source?.toString(),
map!,
true,
) :
new RawSource(result.code || ''),
{
...info,
minimized: true,
} as any,
);
});
if (transforms.length > 0) {
await Promise.all(transforms);
}
}
}
export default ESBuildMinifyPlugin;