-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathEncodingPlugin.js
More file actions
57 lines (49 loc) · 1.96 KB
/
EncodingPlugin.js
File metadata and controls
57 lines (49 loc) · 1.96 KB
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
const fs = require('fs');
const { RawSource, SourceMapSource } = require('webpack-sources');
const encoding = require('encoding');
const { ModuleFilenameHelpers } = require('webpack');
const DEFAULT_OPTIONS = {
test: /(\.js|\.css)($|\?)/i,
};
class EncodingPlugin {
constructor(options = {}) {
this.options = {
...DEFAULT_OPTIONS,
...(typeof options === 'string' ? { encoding: options } : options),
};
}
apply(compiler) {
const { options } = this;
const matchFileName = ModuleFilenameHelpers.matchObject.bind(undefined, options);
compiler.hooks.emit.tapAsync('EncodingPlugin', ({ assets, errors }, callback) => {
Object.keys(assets).filter(matchFileName).forEach(file => {
const asset = assets[file];
let source;
let map;
try {
if (asset.sourceAndMap) {
const sourceAndMap = asset.sourceAndMap();
source = sourceAndMap.source;
map = sourceAndMap.map;
} else {
source = asset.source();
map = typeof asset.map === 'function' ?
asset.map() :
null;
}
const encodedSource = encoding.convert(source, options.encoding, 'UTF-8');
if (asset.existsAt && fs.existsSync(asset.existsAt)) {
fs.writeFileSync(asset.existsAt, encodedSource);
}
assets[file] = map ?
new SourceMapSource(encodedSource, file, map) :
new RawSource(encodedSource);
} catch (e) {
errors.push(new Error(`${file} from EncodingPlugin: ${e.message}`));
}
});
callback();
});
}
}
module.exports = EncodingPlugin;