-
Notifications
You must be signed in to change notification settings - Fork 3
/
bundle-build.js
85 lines (77 loc) · 2.2 KB
/
bundle-build.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
const webpack = require('webpack');
const globber = require('glob');
const { readFile, writeFile } = require('fs');
const buildPattern = process.argv[2];
const glob = (globPattern) => new Promise((r) => {
globber(globPattern, (_, s) => r(s));
});
glob(buildPattern).then((files) => {
const bundle = function bundle(i = 0) {
if (i < files.length) {
const entryFile = files[i];
const outputFile = entryFile.replace('user.js', 'bundle.user.js');
const distFile = `./dist${outputFile.slice(1)}`;
const metaFile = distFile.replace('user.js', 'meta.js');
console.log(entryFile);
console.log(outputFile);
console.log(distFile);
webpack(
{
mode: 'production',
entry: entryFile,
output: {
filename: outputFile,
},
},
(err, stats) => {
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
return;
}
const info = stats.toJson();
if (stats.hasErrors()) {
console.error(info.errors);
}
if (stats.hasWarnings()) {
console.warn(info.warnings);
}
const delimiter = '==/UserScript==\n';
readFile(entryFile, (readEntryFileErr, result) => {
if (readEntryFileErr) {
console.error(readEntryFileErr);
} else if (result.toString().includes(delimiter)) {
const userscriptHeader = result.toString().split(delimiter)[0] + delimiter;
readFile(distFile, (readDistFileErr, distFileContent) => {
if (readDistFileErr) {
console.error(readDistFileErr);
} else {
const bundleWithHeader = userscriptHeader + distFileContent.toString();
writeFile(distFile, bundleWithHeader, (writeDistFileErr) => {
if (writeDistFileErr) {
console.error(writeDistFileErr);
} else {
writeFile(metaFile, userscriptHeader, (writeMetaFileErr) => {
if (writeMetaFileErr) {
console.error(writeMetaFileErr);
} else {
bundle(i + 1);
}
});
}
});
}
});
} else {
console.log('no userscript header');
bundle(i + 1);
}
});
},
);
}
};
bundle();
});