forked from kelyvin/generate-json-from-js-webpack-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (56 loc) · 1.62 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
const path = require('path')
const chalk = require('chalk')
const defaultJsonOptions = {
replacer: null,
space: 2
}
function GenerateJsonFromJsPlugin (config = {}) {
Object.assign(this, {
...config,
filePath: config.path,
filename: config.filename,
data: config.data || [],
options: {
...defaultJsonOptions,
...config.options
}
})
this.plugin = 'GenerateJsonFromJsPlugin'
}
GenerateJsonFromJsPlugin.prototype.apply = function apply (compiler) {
const emit = (compilation, callback) => {
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${chalk.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
}
}
callback()
}
if (compiler.hooks) {
compiler.hooks.emit.tapAsync(this.plugin, emit)
} else {
compiler.plugin('emit', emit)
}
}
module.exports = GenerateJsonFromJsPlugin