-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (61 loc) · 2.96 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
const fs = require("fs");
const _ = require("lodash");
const path = require("path");
class ThemeJsonGeneratorPlugin {
static defaultOptions = {
sourceFile: 'theme.json',
sourceDirectory: '',
filePrefix: 'theme.',
destinationFile: ''
}
constructor(options = {}) {
this.options = {...ThemeJsonGeneratorPlugin.defaultOptions, ...options};
}
apply(compiler) {
const pluginName = 'Theme.json generator';
const {webpack} = compiler;
const {Compilation} = webpack;
const {RawSource} = webpack.sources;
compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: pluginName,
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
},
(assets) => {
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const themeJsonString = fs.readFileSync(`${this.options.sourceDirectory}./${this.options.sourceFile}`, { encoding: 'utf-8'});
const themeJson = JSON.parse(themeJsonString);
const otherFiles = fs.readdirSync(this.options.sourceDirectory);
compilation.fileDependencies.add(path.resolve(`${this.options.sourceDirectory}/${this.options.sourceFile}`));
const fileStrings = [];
for(const file of otherFiles) {
if(!file.endsWith('.json') || !file.startsWith(this.options.filePrefix) || file === this.options.sourceFile) {
continue;
}
compilation.fileDependencies.add(path.resolve(`${this.options.sourceDirectory}/${file}`));
const fileString = fs.readFileSync(`${this.options.sourceDirectory}/${file}`, { encoding: 'utf-8'});
const jsonPath = file.replace('.json', '')
.replace(this.options.filePrefix, '')
.replaceAll('-', '/');
fileStrings.push({
path: jsonPath,
dots: file.match(/\.+/g).length,
data: JSON.parse(fileString)
});
}
fileStrings.sort((a, b) => a.dots - b.dots);
for(const fileString of fileStrings) {
_.set(themeJson, fileString.path, fileString.data);
}
const fileData = JSON.stringify(themeJson, null, 4);
fs.writeFileSync(this.options.destinationFile, fileData);
compilation.emitAsset(this.options.destinationFile, new RawSource(fileData));
}
)
});
}
}
module.exports.default = ThemeJsonGeneratorPlugin;