123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655 |
- 'use strict';
- var vm = require('vm');
- var fs = require('fs');
- var _ = require('lodash');
- var Promise = require('bluebird');
- var path = require('path');
- var childCompiler = require('./lib/compiler.js');
- var prettyError = require('./lib/errors.js');
- var chunkSorter = require('./lib/chunksorter.js');
- Promise.promisifyAll(fs);
- function HtmlWebpackPlugin (options) {
-
- this.options = _.extend({
- template: path.join(__dirname, 'default_index.ejs'),
- filename: 'index.html',
- hash: false,
- inject: true,
- compile: true,
- favicon: false,
- minify: false,
- cache: true,
- showErrors: true,
- chunks: 'all',
- excludeChunks: [],
- title: 'Webpack App',
- xhtml: false
- }, options);
- }
- HtmlWebpackPlugin.prototype.apply = function (compiler) {
- var self = this;
- var isCompilationCached = false;
- var compilationPromise;
- this.options.template = this.getFullTemplatePath(this.options.template, compiler.context);
-
-
- var filename = this.options.filename;
- if (path.resolve(filename) === path.normalize(filename)) {
- this.options.filename = path.relative(compiler.options.output.path, filename);
- }
- compiler.plugin('make', function (compilation, callback) {
-
- compilationPromise = childCompiler.compileTemplate(self.options.template, compiler.context, self.options.filename, compilation)
- .catch(function (err) {
- compilation.errors.push(prettyError(err, compiler.context).toString());
- return {
- content: self.options.showErrors ? prettyError(err, compiler.context).toJsonHtml() : 'ERROR',
- outputName: self.options.filename
- };
- })
- .then(function (compilationResult) {
-
- isCompilationCached = compilationResult.hash && self.childCompilerHash === compilationResult.hash;
- self.childCompilerHash = compilationResult.hash;
- self.childCompilationOutputName = compilationResult.outputName;
- callback();
- return compilationResult.content;
- });
- });
- compiler.plugin('emit', function (compilation, callback) {
- var applyPluginsAsyncWaterfall = self.applyPluginsAsyncWaterfall(compilation);
-
- var allChunks = compilation.getStats().toJson().chunks;
-
- var chunks = self.filterChunks(allChunks, self.options.chunks, self.options.excludeChunks);
-
- chunks = self.sortChunks(chunks, self.options.chunksSortMode);
-
- chunks = compilation.applyPluginsWaterfall('html-webpack-plugin-alter-chunks', chunks, { plugin: self });
-
- var assets = self.htmlWebpackPluginAssets(compilation, chunks);
-
-
-
- if (self.isHotUpdateCompilation(assets)) {
- return callback();
- }
-
- var assetJson = JSON.stringify(self.getAssetFiles(assets));
- if (isCompilationCached && self.options.cache && assetJson === self.assetJson) {
- return callback();
- } else {
- self.assetJson = assetJson;
- }
- Promise.resolve()
-
- .then(function () {
- if (self.options.favicon) {
- return self.addFileToAssets(self.options.favicon, compilation)
- .then(function (faviconBasename) {
- var publicPath = compilation.mainTemplate.getPublicPath({hash: compilation.hash}) || '';
- if (publicPath && publicPath.substr(-1) !== '/') {
- publicPath += '/';
- }
- assets.favicon = publicPath + faviconBasename;
- });
- }
- })
-
- .then(function () {
- return compilationPromise;
- })
- .then(function (compiledTemplate) {
-
- if (self.options.templateContent !== undefined) {
- return self.options.templateContent;
- }
-
-
- return self.evaluateCompilationResult(compilation, compiledTemplate);
- })
-
-
- .then(function (compilationResult) {
- return applyPluginsAsyncWaterfall('html-webpack-plugin-before-html-generation', false, {
- assets: assets,
- outputName: self.childCompilationOutputName,
- plugin: self
- })
- .then(function () {
- return compilationResult;
- });
- })
-
- .then(function (compilationResult) {
-
-
- return typeof compilationResult !== 'function'
- ? compilationResult
- : self.executeTemplate(compilationResult, chunks, assets, compilation);
- })
-
- .then(function (html) {
- var pluginArgs = {html: html, assets: assets, plugin: self, outputName: self.childCompilationOutputName};
- return applyPluginsAsyncWaterfall('html-webpack-plugin-before-html-processing', true, pluginArgs);
- })
- .then(function (result) {
- var html = result.html;
- var assets = result.assets;
-
- var assetTags = self.generateAssetTags(assets);
- var pluginArgs = {head: assetTags.head, body: assetTags.body, plugin: self, chunks: chunks, outputName: self.childCompilationOutputName};
-
- return applyPluginsAsyncWaterfall('html-webpack-plugin-alter-asset-tags', true, pluginArgs)
- .then(function (result) {
-
- return self.postProcessHtml(html, assets, { body: result.body, head: result.head })
- .then(function (html) {
- return _.extend(result, {html: html, assets: assets});
- });
- });
- })
-
- .then(function (result) {
- var html = result.html;
- var assets = result.assets;
- var pluginArgs = {html: html, assets: assets, plugin: self, outputName: self.childCompilationOutputName};
- return applyPluginsAsyncWaterfall('html-webpack-plugin-after-html-processing', true, pluginArgs)
- .then(function (result) {
- return result.html;
- });
- })
- .catch(function (err) {
-
-
- compilation.errors.push(prettyError(err, compiler.context).toString());
-
- self.hash = null;
- return self.options.showErrors ? prettyError(err, compiler.context).toHtml() : 'ERROR';
- })
- .then(function (html) {
-
- compilation.assets[self.childCompilationOutputName] = {
- source: function () {
- return html;
- },
- size: function () {
- return html.length;
- }
- };
- })
- .then(function () {
-
- return applyPluginsAsyncWaterfall('html-webpack-plugin-after-emit', false, {
- html: compilation.assets[self.childCompilationOutputName],
- outputName: self.childCompilationOutputName,
- plugin: self
- }).catch(function (err) {
- console.error(err);
- return null;
- }).then(function () {
- return null;
- });
- })
-
- .finally(function () {
- callback();
-
-
-
- return null;
- });
- });
- };
- HtmlWebpackPlugin.prototype.evaluateCompilationResult = function (compilation, source) {
- if (!source) {
- return Promise.reject('The child compilation didn\'t provide a result');
- }
-
-
- source = source.replace('var HTML_WEBPACK_PLUGIN_RESULT =', '');
- var template = this.options.template.replace(/^.+!/, '').replace(/\?.+$/, '');
- var vmContext = vm.createContext(_.extend({HTML_WEBPACK_PLUGIN: true, require: require}, global));
- var vmScript = new vm.Script(source, {filename: template});
-
- var newSource;
- try {
- newSource = vmScript.runInContext(vmContext);
- } catch (e) {
- return Promise.reject(e);
- }
- if (typeof newSource === 'object' && newSource.__esModule && newSource.default) {
- newSource = newSource.default;
- }
- return typeof newSource === 'string' || typeof newSource === 'function'
- ? Promise.resolve(newSource)
- : Promise.reject('The loader "' + this.options.template + '" didn\'t return html.');
- };
- HtmlWebpackPlugin.prototype.executeTemplate = function (templateFunction, chunks, assets, compilation) {
- var self = this;
- return Promise.resolve()
-
- .then(function () {
- var templateParams = {
- compilation: compilation,
- webpack: compilation.getStats().toJson(),
- webpackConfig: compilation.options,
- htmlWebpackPlugin: {
- files: assets,
- options: self.options
- }
- };
- var html = '';
- try {
- html = templateFunction(templateParams);
- } catch (e) {
- compilation.errors.push(new Error('Template execution failed: ' + e));
- return Promise.reject(e);
- }
- return html;
- });
- };
- HtmlWebpackPlugin.prototype.postProcessHtml = function (html, assets, assetTags) {
- var self = this;
- if (typeof html !== 'string') {
- return Promise.reject('Expected html to be a string but got ' + JSON.stringify(html));
- }
- return Promise.resolve()
-
- .then(function () {
- if (self.options.inject) {
- return self.injectAssetsIntoHtml(html, assets, assetTags);
- } else {
- return html;
- }
- })
-
- .then(function (html) {
- if (self.options.minify) {
- var minify = require('html-minifier').minify;
- return minify(html, self.options.minify);
- }
- return html;
- });
- };
- HtmlWebpackPlugin.prototype.addFileToAssets = function (filename, compilation) {
- filename = path.resolve(compilation.compiler.context, filename);
- return Promise.props({
- size: fs.statAsync(filename),
- source: fs.readFileAsync(filename)
- })
- .catch(function () {
- return Promise.reject(new Error('HtmlWebpackPlugin: could not load file ' + filename));
- })
- .then(function (results) {
- var basename = path.basename(filename);
- compilation.fileDependencies.push(filename);
- compilation.assets[basename] = {
- source: function () {
- return results.source;
- },
- size: function () {
- return results.size.size;
- }
- };
- return basename;
- });
- };
- HtmlWebpackPlugin.prototype.sortChunks = function (chunks, sortMode) {
-
- if (typeof sortMode === 'undefined') {
- sortMode = 'auto';
- }
-
- if (typeof sortMode === 'function') {
- return chunks.sort(sortMode);
- }
-
- if (sortMode === 'none') {
- return chunkSorter.none(chunks);
- }
-
- if (typeof chunkSorter[sortMode] !== 'undefined') {
- return chunkSorter[sortMode](chunks, this.options.chunks);
- }
- throw new Error('"' + sortMode + '" is not a valid chunk sort mode');
- };
- HtmlWebpackPlugin.prototype.filterChunks = function (chunks, includedChunks, excludedChunks) {
- return chunks.filter(function (chunk) {
- var chunkName = chunk.names[0];
-
- if (chunkName === undefined) {
- return false;
- }
-
- if (typeof chunk.isInitial === 'function') {
- if (!chunk.isInitial()) {
- return false;
- }
- } else if (!chunk.initial) {
- return false;
- }
-
- if (Array.isArray(includedChunks) && includedChunks.indexOf(chunkName) === -1) {
- return false;
- }
-
- if (Array.isArray(excludedChunks) && excludedChunks.indexOf(chunkName) !== -1) {
- return false;
- }
-
- return true;
- });
- };
- HtmlWebpackPlugin.prototype.isHotUpdateCompilation = function (assets) {
- return assets.js.length && assets.js.every(function (name) {
- return /\.hot-update\.js$/.test(name);
- });
- };
- HtmlWebpackPlugin.prototype.htmlWebpackPluginAssets = function (compilation, chunks) {
- var self = this;
- var compilationHash = compilation.hash;
-
- var publicPath = typeof compilation.options.output.publicPath !== 'undefined'
-
- ? compilation.mainTemplate.getPublicPath({hash: compilationHash})
-
- : path.relative(path.resolve(compilation.options.output.path, path.dirname(self.childCompilationOutputName)), compilation.options.output.path)
- .split(path.sep).join('/');
- if (publicPath.length && publicPath.substr(-1, 1) !== '/') {
- publicPath += '/';
- }
- var assets = {
-
- publicPath: publicPath,
-
- chunks: {},
-
- js: [],
-
- css: [],
-
- manifest: Object.keys(compilation.assets).filter(function (assetFile) {
- return path.extname(assetFile) === '.appcache';
- })[0]
- };
-
- if (this.options.hash) {
- assets.manifest = self.appendHash(assets.manifest, compilationHash);
- assets.favicon = self.appendHash(assets.favicon, compilationHash);
- }
- for (var i = 0; i < chunks.length; i++) {
- var chunk = chunks[i];
- var chunkName = chunk.names[0];
- assets.chunks[chunkName] = {};
-
- var chunkFiles = [].concat(chunk.files).map(function (chunkFile) {
- return publicPath + chunkFile;
- });
-
- if (this.options.hash) {
- chunkFiles = chunkFiles.map(function (chunkFile) {
- return self.appendHash(chunkFile, compilationHash);
- });
- }
-
-
- var entry = chunkFiles[0];
- assets.chunks[chunkName].size = chunk.size;
- assets.chunks[chunkName].entry = entry;
- assets.chunks[chunkName].hash = chunk.hash;
- assets.js.push(entry);
-
- var css = chunkFiles.filter(function (chunkFile) {
-
-
- return /.css($|\?)/.test(chunkFile);
- });
- assets.chunks[chunkName].css = css;
- assets.css = assets.css.concat(css);
- }
-
-
- assets.css = _.uniq(assets.css);
- return assets;
- };
- HtmlWebpackPlugin.prototype.generateAssetTags = function (assets) {
-
- var scripts = assets.js.map(function (scriptPath) {
- return {
- tagName: 'script',
- closeTag: true,
- attributes: {
- type: 'text/javascript',
- src: scriptPath
- }
- };
- });
-
- var selfClosingTag = !!this.options.xhtml;
-
- var styles = assets.css.map(function (stylePath) {
- return {
- tagName: 'link',
- selfClosingTag: selfClosingTag,
- attributes: {
- href: stylePath,
- rel: 'stylesheet'
- }
- };
- });
-
- var head = [];
- var body = [];
-
- if (assets.favicon) {
- head.push({
- tagName: 'link',
- selfClosingTag: selfClosingTag,
- attributes: {
- rel: 'shortcut icon',
- href: assets.favicon
- }
- });
- }
-
- head = head.concat(styles);
-
- if (this.options.inject === 'head') {
- head = head.concat(scripts);
- } else {
- body = body.concat(scripts);
- }
- return {head: head, body: body};
- };
- HtmlWebpackPlugin.prototype.injectAssetsIntoHtml = function (html, assets, assetTags) {
- var htmlRegExp = /(<html[^>]*>)/i;
- var headRegExp = /(<\/head\s*>)/i;
- var bodyRegExp = /(<\/body\s*>)/i;
- var body = assetTags.body.map(this.createHtmlTag);
- var head = assetTags.head.map(this.createHtmlTag);
- if (body.length) {
- if (bodyRegExp.test(html)) {
-
- html = html.replace(bodyRegExp, function (match) {
- return body.join('') + match;
- });
- } else {
-
- html += body.join('');
- }
- }
- if (head.length) {
-
- if (!headRegExp.test(html)) {
- if (!htmlRegExp.test(html)) {
- html = '<head></head>' + html;
- } else {
- html = html.replace(htmlRegExp, function (match) {
- return match + '<head></head>';
- });
- }
- }
-
- html = html.replace(headRegExp, function (match) {
- return head.join('') + match;
- });
- }
-
- if (assets.manifest) {
- html = html.replace(/(<html[^>]*)(>)/i, function (match, start, end) {
-
- if (/\smanifest\s*=/.test(match)) {
- return match;
- }
- return start + ' manifest="' + assets.manifest + '"' + end;
- });
- }
- return html;
- };
- HtmlWebpackPlugin.prototype.appendHash = function (url, hash) {
- if (!url) {
- return url;
- }
- return url + (url.indexOf('?') === -1 ? '?' : '&') + hash;
- };
- HtmlWebpackPlugin.prototype.createHtmlTag = function (tagDefinition) {
- var attributes = Object.keys(tagDefinition.attributes || {})
- .filter(function (attributeName) {
- return tagDefinition.attributes[attributeName] !== false;
- })
- .map(function (attributeName) {
- if (tagDefinition.attributes[attributeName] === true) {
- return attributeName;
- }
- return attributeName + '="' + tagDefinition.attributes[attributeName] + '"';
- });
-
- var voidTag = tagDefinition.voidTag !== undefined ? tagDefinition.voidTag : !tagDefinition.closeTag;
- var selfClosingTag = tagDefinition.voidTag !== undefined ? tagDefinition.voidTag && this.options.xhtml : tagDefinition.selfClosingTag;
- return '<' + [tagDefinition.tagName].concat(attributes).join(' ') + (selfClosingTag ? '/' : '') + '>' +
- (tagDefinition.innerHTML || '') +
- (voidTag ? '' : '</' + tagDefinition.tagName + '>');
- };
- HtmlWebpackPlugin.prototype.getFullTemplatePath = function (template, context) {
-
- if (template.indexOf('!') === -1) {
- template = require.resolve('./lib/loader.js') + '!' + path.resolve(context, template);
- }
-
- return template.replace(
- /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/,
- function (match, prefix, filepath, postfix) {
- return prefix + path.resolve(filepath) + postfix;
- });
- };
- HtmlWebpackPlugin.prototype.getAssetFiles = function (assets) {
- var files = _.uniq(Object.keys(assets).filter(function (assetType) {
- return assetType !== 'chunks' && assets[assetType];
- }).reduce(function (files, assetType) {
- return files.concat(assets[assetType]);
- }, []));
- files.sort();
- return files;
- };
- HtmlWebpackPlugin.prototype.applyPluginsAsyncWaterfall = function (compilation) {
- var promisedApplyPluginsAsyncWaterfall = Promise.promisify(compilation.applyPluginsAsyncWaterfall, {context: compilation});
- return function (eventName, requiresResult, pluginArgs) {
- return promisedApplyPluginsAsyncWaterfall(eventName, pluginArgs)
- .then(function (result) {
- if (requiresResult && !result) {
- compilation.warnings.push(new Error('Using ' + eventName + ' without returning a result is deprecated.'));
- }
- return _.extend(pluginArgs, result);
- });
- };
- };
- module.exports = HtmlWebpackPlugin;
|