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