forked from cqqccqc/webpack-utf8-bom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebpack-utf8-bom.js
53 lines (46 loc) · 1.59 KB
/
webpack-utf8-bom.js
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
/* global Buffer */
const fs = require('fs');
const path = require('path');
function UTF8BOMPlugin(addBOM, fileMask) {
this.fileMask = fileMask || /\.(html|htm|css|js|map)$/;
this.addBOM = addBOM;
}
UTF8BOMPlugin.prototype.apply = function(compiler) {
compiler.hooks.done.tap('UTF8BOMPlugin', (stats) => {
const outputPath = stats.compilation.outputOptions.path;
const files = stats.compilation.assets;
const logger = compiler.getInfrastructureLogger('UTF8BOMPlugin');
for (const fileName in files) {
if (!fileName.match(this.fileMask)) {
continue;
}
const existingFilePath = path.resolve(outputPath, fileName);
let buff = fs.readFileSync(existingFilePath);
if (this.addBOM) {
logger.log('Add BOM: ' + fileName);
if (
buff.length < 3 ||
buff[0].toString(16).toLowerCase() !== 'ef' ||
buff[1].toString(16).toLowerCase() !== 'bb' ||
buff[2].toString(16).toLowerCase() !== 'bf'
) {
const bom = Buffer.from([0xef, 0xbb, 0xbf]);
buff = bom + buff;
fs.writeFileSync(existingFilePath, buff.toString(), 'utf8');
}
} else {
logger.log('Remove BOM: ' + fileName);
if (
buff.length >= 3 &&
buff[0].toString(16).toLowerCase() === 'ef' &&
buff[1].toString(16).toLowerCase() === 'bb' &&
buff[2].toString(16).toLowerCase() === 'bf'
) {
buff = buff.slice(3);
fs.writeFileSync(existingFilePath, buff.toString(), 'utf8');
}
}
}
});
};
module.exports = UTF8BOMPlugin;