-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
62 lines (58 loc) · 1.74 KB
/
index.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
54
55
56
57
58
59
60
61
62
const fs = require('fs-extra');
const path = require('path');
const package = require(path.resolve(process.cwd(), 'package.json'));
let config;
if (package['parcel-plugin-change-file']) {
config = package['parcel-plugin-change-file'];
} else if (fs.existsSync(configFilePath)) {
config = require(configFilePath);
} else {
console.log(
'No find parcel-plugin-change-file in package.json or parcel-plugin-change-file.js',
);
return;
}
let isCopyed = false;
function changeHtml(filePath) {
let data = fs.readFileSync(filePath, { encoding: 'utf-8' });
if (config && config.html && config.html.length > 0) {
for (let i = 0, l = config.html.length; i <= l; i++) {
const exp = eval(
`/<!-- ${config.replaceName || 'parcel-plugin-change-file'}-${i} -->/g`,
);
data = data.replace(exp, config.html[i]);
}
}
data = data.replace(/<!--\|/g, '');
data = data.replace(/\|-->/g, '');
data = data.replace(/<!--\[/g, '');
data = data.replace(/\]-->/g, '');
setTimeout(() => {
fs.removeSync(filePath);
fs.createFileSync(filePath);
fs.writeFileSync(filePath, data);
}, config.timeout || 30);
}
function copyFiles(outPath) {
if (config && config.copy && config.copy.length > 0) {
for (var i = 0, l = config.copy.length; i < l; i++) {
const ele = config.copy[i];
const targetPath = path.resolve(process.cwd(), ele);
fs.copySync(targetPath, outPath);
}
}
}
module.exports = function(bundler) {
if (process.env.changeFile != 'false') {
bundler.on('bundled', bund => {
const bundleDir = path.dirname(bund.name);
if (bund.type === 'html') {
changeHtml(bund.name);
}
if (!isCopyed) {
isCopyed = true;
copyFiles(bundleDir);
}
});
}
};