-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
64 lines (54 loc) · 1.52 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
const { getGitCommitId } = require('./helper');
class GitHashWebpackPlugin {
constructor(options = {}) {
this.defaultOptions = {
len: 0,
webpack: null,
};
this.options = {
...this.defaultOptions,
...options,
};
}
initDefinePlugin(ctx, options) {
if (!options.plugins) {
options.plugins = [];
}
for (let i = 0; i < options.plugins.length; i++) {
const plugin = options.plugins[i];
if (plugin instanceof ctx.DefinePlugin) return;
}
options.plugins.push(new ctx.DefinePlugin({}));
}
injectDefineHash(ctx, options) {
const hash = getGitCommitId().slice(
0,
this.options.len ? this.options.len : -1
);
options.plugins.forEach((plugin) => {
if (plugin instanceof ctx.DefinePlugin) {
if (!plugin.definitions) {
plugin.definitions = {};
}
const definedProcessEnv = plugin.definitions['process.env'];
if (definedProcessEnv) {
definedProcessEnv.COMMIT = JSON.stringify(hash);
} else {
plugin.definitions['process.env.COMMIT'] = JSON.stringify(hash);
}
}
});
}
apply(compiler) {
const name = GitHashWebpackPlugin.name;
let { webpack, options } = compiler;
if (!webpack && this.options.webpack) {
webpack = this.options.webpack;
}
this.initDefinePlugin(webpack, options);
compiler.hooks.beforeCompile.tap(name, () => {
this.injectDefineHash(webpack, options);
});
}
}
module.exports = GitHashWebpackPlugin;