-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
70 lines (61 loc) · 1.76 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
const PLUGIN_NAME = "GenerateJsonFromJsPlugin";
const path = require("path");
const defaultJsonOptions = {
replacer: null,
space: 2,
};
class GenerateJsonFromJsPlugin {
constructor(config = {}) {
Object.assign(this, {
...config,
filePath: config.path,
filename: config.filename,
data: config.data || [],
options: {
...defaultJsonOptions,
...config.options,
},
});
this.plugin = PLUGIN_NAME;
}
apply(compiler) {
const emit = (compilation) => {
const fullFilePath = path.resolve(compiler.context, this.filePath);
// Adding this causes a "rebuild" when the template file changes and indicate when the file has changed
compilation.fileDependencies.add(fullFilePath);
process.stdout.write(`\n${green("Rebuilding ")}${this.filename}\n`);
const jsModule = require(fullFilePath);
let jsonValue = null;
if (typeof jsModule === "function") {
jsonValue = jsModule(this.data);
} else if (jsModule instanceof Array) {
jsonValue = [...jsModule, ...this.data];
} else if (typeof jsModule === "object") {
jsonValue = {
...jsModule,
...this.data,
};
}
if (jsonValue) {
const json = JSON.stringify(
jsonValue,
this.options.replacer,
this.options.space
);
compilation.assets[this.filename] = {
source: () => json,
size: () => json.length,
};
}
};
if (compiler.hooks) {
compiler.hooks.thisCompilation.tap(this.plugin, emit);
} else {
compiler.plugin("emit", emit);
}
}
}
module.exports = GenerateJsonFromJsPlugin;
function green(str) {
return "\u001b[1m\u001b[32m" + str + "\u001b[39m\u001b[22m";
}