forked from kossnocorp/on-build-webpack
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
63 lines (55 loc) · 1.64 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
// TODO tests for _dashToCamelCase and _camelCaseToDash
/**
* @module BeforeBuildWebpackPlugin
*/
/**
* @constructor
* @param {onBuildCallback} callback - will be called on specified event of webpack ("before run" by default).
*/
function WebpackBeforeBuildPlugin(callback, eventNames) {
this.callback = callback;
this.eventNames = eventNames || ["run", "watch-run"];
if (!(this.eventNames instanceof Array)) this.eventNames = [this.eventNames];
};
/**
* @callback beforeBuildCallback
* @param {object} compiler - webpack compiler object
*/
WebpackBeforeBuildPlugin.prototype.apply = function (compiler) {
for (var i in this.eventNames) {
_applyPlugin(compiler, this.eventNames[i], this.callback);
}
};
function _applyPlugin (compiler, eventName, fn) {
if (!compiler.hooks) {
//webpack v1-3
eventName = _camelCaseToDash(eventName);
compiler.plugin(eventName, (compiler, callback) => {
fn(compiler, callback || function(){});
});
} else {
//webpack v4
eventName = _dashToCamelCase(eventName);
if (compiler.hooks[eventName]) {
compiler.hooks[eventName].tapAsync({ name: "before-build-webpack-plugin" }, (tap, callback) => {
fn(tap, callback);
});
}
}
}
/**
* Converts "aaa-bbb-ccc" to "aaaBbbCcc"
*/
function _dashToCamelCase (string) {
return string.replace(/-([a-z])/g, (all, letter) => {
return letter.toUpperCase();
});
}
/**
* Converts "aaaBbbCcc" to "aaa-bbb-ccc"
* [source https://gist.github.com/youssman/745578062609e8acac9f]
*/
function _camelCaseToDash( myStr ) {
return myStr.replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();
}
module.exports = WebpackBeforeBuildPlugin;