forked from jantimon/html-webpack-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
77 lines (66 loc) · 2.52 KB
/
index.js
File metadata and controls
77 lines (66 loc) · 2.52 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
70
71
72
73
74
75
76
77
var fs = require('fs');
var path = require('path');
var tmpl = require('blueimp-tmpl').tmpl;
function HtmlWebpackPlugin(options) {
this.options = options || {};
}
HtmlWebpackPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('emit', function(compiler, callback) {
var webpackStatsJson = compiler.getStats().toJson();
var templateParams = {};
templateParams.webpack = webpackStatsJson;
templateParams.htmlWebpackPlugin = {};
templateParams.htmlWebpackPlugin.assets = self.htmlWebpackPluginAssets(compiler, webpackStatsJson);
templateParams.htmlWebpackPlugin.options = self.options;
var outputFilename = self.options.filename || 'index.html';
if (self.options.templateContent && self.options.template) {
compiler.errors.push(new Error('HtmlWebpackPlugin: cannot specify both template and templateContent options'));
callback();
} else if (self.options.templateContent) {
self.emitHtml(compiler, self.options.templateContent, templateParams, outputFilename);
callback();
} else {
var templateFile = self.options.template;
if (!templateFile) {
templateFile = path.join(__dirname, 'default_index.html');
}
fs.readFile(templateFile, 'utf8', function(err, htmlTemplateContent) {
if (err) {
compiler.errors.push(new Error('HtmlWebpackPlugin: Unable to read HTML template "' + templateFile + '"'));
} else {
self.emitHtml(compiler, htmlTemplateContent, templateParams, outputFilename);
}
callback();
});
}
});
};
HtmlWebpackPlugin.prototype.emitHtml = function(compiler, htmlTemplateContent, templateParams, outputFilename) {
var html = tmpl(htmlTemplateContent, templateParams);
compiler.assets[outputFilename] = {
source: function() {
return html;
},
size: function() {
return html.length;
}
};
};
HtmlWebpackPlugin.prototype.htmlWebpackPluginAssets = function(compiler, webpackStatsJson) {
var assets = {};
for (var chunk in webpackStatsJson.assetsByChunkName) {
var chunkValue = webpackStatsJson.assetsByChunkName[chunk];
// Webpack outputs an array for each chunk when using sourcemaps
if (chunkValue instanceof Array) {
// Is the main bundle always the first element?
chunkValue = chunkValue[0];
}
if (compiler.options.output.publicPath) {
chunkValue = compiler.options.output.publicPath + chunkValue;
}
assets[chunk] = chunkValue;
}
return assets;
};
module.exports = HtmlWebpackPlugin;