-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (71 loc) · 2.75 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
83
84
85
'use strict';
const PLUGIN_NAME = 'hiw';
const END_LINE = require('os').EOL;
const weblog = require('webpack-log');
const path = require('path');
const log = weblog({
name: PLUGIN_NAME
});
const headerInjectionWebpackPluginDefaultOptions = {
package: './package.json',
extensions: ['.js', '.html', '.css'],
headers: {
js: (comment) => `/*! ${comment} */`,
html: (comment) => `<!-- ${comment} -->`,
css: (comment) => `/** ${comment} **/`,
}
};
class HeaderInjectionWebpackPlugin {
constructor(options) {
this.options = Object.assign({}, headerInjectionWebpackPluginDefaultOptions, options);
this.getDefaultHeader = this.getDefaultHeader.bind(this);
this.handleCompilation = this.handleCompilation.bind(this);
this.attachHeaderToAsset = this.attachHeaderToAsset.bind(this);
this.apply = this.apply.bind(this);
if (!this.options.header) {
this.options.header = this.getDefaultHeader;
}
}
getDefaultHeader() {
const app = require(path.resolve(process.cwd(), this.options.package));
return `[${PLUGIN_NAME}] ${app.name} / ${app.version} / ${new Date().toISOString()}`;
}
attachHeaderToAsset(filename, compilation) {
var opts = this.options;
var ext = '.' + filename.split('.').pop();
if (!opts.extensions.includes(ext)) {
return false;
}
var header = opts.headers[ext.substr(1)](typeof opts.header === 'function' ? opts.header() : opts.header);
var asset = compilation.assets[filename];
var originSource = asset.source();
var finalSource = `${header}${END_LINE}${originSource}`;
asset.source = () => finalSource;
log.info(`Injecting header for ${filename}: ${header}`);
return true;
}
handleCompilation(compilation, callback) {
log.info(`Injecting header for ${this.options.extensions} files ...`);
var self = this;
// compilation.chunks.forEach(function (chunk) {
// // Explore each asset filename generated by the chunk:
// chunk.files.forEach(function (filename) {
// // Get the asset source for each file generated by the chunk:
// });
// });
// below include chunk files
let count = 0;
for (var filename in compilation.assets) {
self.attachHeaderToAsset(filename, compilation) && count++;
}
if (typeof callback === 'function') {
callback();
}
log.info(`${count} file(s) done`);
}
apply(compiler) {
compiler.hooks.emit.tapAsync(PLUGIN_NAME, this.handleCompilation);
// compiler.plugin('emit', this.handleCompilation);
}
}
module.exports = HeaderInjectionWebpackPlugin;