forked from levp/wrapper-webpack-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrapper-webpack-plugin.js
More file actions
69 lines (59 loc) · 2 KB
/
wrapper-webpack-plugin.js
File metadata and controls
69 lines (59 loc) · 2 KB
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
'use strict';
var ConcatSource = require("webpack-sources").ConcatSource;
var ModuleFilenameHelpers = require("webpack/lib/ModuleFilenameHelpers");
/**
* @param args
* @param {string|function} [args.header]
* @param {string|function} [args.footer]
* @param {string|RegExp} [args.test]
* @param {boolean} [args.runAfterOptimize=false]
* @constructor
*/
function WrapperPlugin(args) {
if (typeof args !== 'object') {
throw new TypeError('Argument "args" must be an object.');
}
this.header = args.hasOwnProperty('header') ? args.header : '';
this.footer = args.hasOwnProperty('footer') ? args.footer : '';
this.test = args.hasOwnProperty('test') ? args.test : '';
this.runAfterOptimize = args.hasOwnProperty('runAfterOptimize') ? args.runAfterOptimize : false;
}
function apply(compiler) {
var header = this.header;
var footer = this.footer;
var tester = {test: this.test};
var runAfterOptimize = this.runAfterOptimize
compiler.plugin('compilation', function (compilation) {
if (runAfterOptimize)
compilation.plugin('after-optimize-chunk-assets', function (chunks) {
wrapChunks(compilation, chunks, footer, header);
})
else
compilation.plugin('optimize-chunk-assets', function (chunks, done) {
wrapChunks(compilation, chunks, footer, header);
done();
})
});
function wrapFile(compilation, fileName) {
var headerContent = (typeof header === 'function') ? header(fileName) : header;
var footerContent = (typeof footer === 'function') ? footer(fileName) : footer;
compilation.assets[fileName] = new ConcatSource(
String(headerContent),
compilation.assets[fileName],
String(footerContent));
}
function wrapChunks(compilation, chunks) {
chunks.forEach(function (chunk) {
chunk.files.forEach(function (fileName) {
if (ModuleFilenameHelpers.matchObject(tester, fileName)) {
wrapFile(compilation, fileName);
}
});
});
}
}
Object.defineProperty(WrapperPlugin.prototype, 'apply', {
value: apply,
enumerable: false
});
module.exports = WrapperPlugin;