forked from oyslin/replace-in-file-webpack-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (79 loc) · 2.04 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
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
const pluginName = 'ReplaceInSrcWebpackPlugin';
const path = require('path');
const fs = require('fs');
class ReplaceInSrcWebpackPlugin {
constructor(options) {
if (typeof options !== 'object') {
throw new Error('"options" must be an object.');
}
this.options = options;
this.apply = this.apply.bind(this);
}
apply(compiler) {
compiler.hooks.done.tap(pluginName, () => {
try {
const output = compiler.outputPath;
this.options.forEach(option => {
const dir = option.dir || output;
if (option.files) {
const files = option.files;
if (Array.isArray(files) && files.length) {
files.forEach(file => {
this.replace(path.resolve(dir, file), option.rules);
})
}
} else if (option.test) {
const test = option.test;
const testArray = Array.isArray(test) ? test : [test];
const files = this.getAllFiles(dir);
files.forEach(file => {
const match = testArray.some(test => {
return test.test(file);
})
if (!match) {
return;
}
this.replace(file, option.rules);
})
} else {
const files = this.getAllFiles(dir);
files.forEach(file => {
this.replace(file, option.rules);
});
}
});
} catch (e) {
console.log(`${pluginName} - > error`, e);
}
});
}
getAllFiles(dir) {
const files = fs.readdirSync(dir);
let res = [];
files.forEach(file => {
const pathname = dir + '/' + file,
stat = fs.lstatSync(pathname);
if (!stat.isDirectory()) {
res.push(pathname);
} else {
res = res.concat(getAllFiles(pathname));
}
});
return res
}
replace(file, rules) {
const src = path.resolve(file);
let template = fs.readFileSync(src, 'utf8');
template = rules.reduce(
(template, rule) => template.replace(
rule.search,
(typeof rule.replace === 'string'
? rule.replace
: rule.replace.bind({ file: path.basename(file) }))
),
template
);
fs.writeFileSync(src, template);
}
}
module.exports = ReplaceInSrcWebpackPlugin;