123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729 |
- 'use strict';
- const promisify = require('util.promisify');
- const vm = require('vm');
- const fs = require('fs');
- const _ = require('lodash');
- const path = require('path');
- const childCompiler = require('./lib/compiler.js');
- const prettyError = require('./lib/errors.js');
- const chunkSorter = require('./lib/chunksorter.js');
- const fsStatAsync = promisify(fs.stat);
- const fsReadFileAsync = promisify(fs.readFile);
- class HtmlWebpackPlugin {
- constructor (options) {
-
- this.options = _.extend({
- template: path.join(__dirname, 'default_index.ejs'),
- templateParameters: templateParametersGenerator,
- filename: 'index.html',
- hash: false,
- inject: true,
- compile: true,
- favicon: false,
- minify: false,
- cache: true,
- showErrors: true,
- chunks: 'all',
- excludeChunks: [],
- chunksSortMode: 'auto',
- meta: {},
- title: 'Webpack App',
- xhtml: false
- }, options);
- }
- apply (compiler) {
- const self = this;
- let isCompilationCached = false;
- let compilationPromise;
- this.options.template = this.getFullTemplatePath(this.options.template, compiler.context);
-
-
- const filename = this.options.filename;
- if (path.resolve(filename) === path.normalize(filename)) {
- this.options.filename = path.relative(compiler.options.output.path, filename);
- }
-
- if (compiler.hooks) {
- compiler.hooks.compilation.tap('HtmlWebpackPluginHooks', compilation => {
- const SyncWaterfallHook = require('tapable').SyncWaterfallHook;
- const AsyncSeriesWaterfallHook = require('tapable').AsyncSeriesWaterfallHook;
- compilation.hooks.htmlWebpackPluginAlterChunks = new SyncWaterfallHook(['chunks', 'objectWithPluginRef']);
- compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration = new AsyncSeriesWaterfallHook(['pluginArgs']);
- compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing = new AsyncSeriesWaterfallHook(['pluginArgs']);
- compilation.hooks.htmlWebpackPluginAlterAssetTags = new AsyncSeriesWaterfallHook(['pluginArgs']);
- compilation.hooks.htmlWebpackPluginAfterHtmlProcessing = new AsyncSeriesWaterfallHook(['pluginArgs']);
- compilation.hooks.htmlWebpackPluginAfterEmit = new AsyncSeriesWaterfallHook(['pluginArgs']);
- });
- }
-
- (compiler.hooks ? compiler.hooks.make.tapAsync.bind(compiler.hooks.make, 'HtmlWebpackPlugin') : compiler.plugin.bind(compiler, 'make'))((compilation, callback) => {
-
- compilationPromise = childCompiler.compileTemplate(self.options.template, compiler.context, self.options.filename, compilation)
- .catch(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(compilationResult => {
-
- isCompilationCached = compilationResult.hash && self.childCompilerHash === compilationResult.hash;
- self.childCompilerHash = compilationResult.hash;
- self.childCompilationOutputName = compilationResult.outputName;
- callback();
- return compilationResult.content;
- });
- });
-
- (compiler.hooks ? compiler.hooks.emit.tapAsync.bind(compiler.hooks.emit, 'HtmlWebpackPlugin') : compiler.plugin.bind(compiler, 'emit'))((compilation, callback) => {
- const applyPluginsAsyncWaterfall = self.applyPluginsAsyncWaterfall(compilation);
-
-
- const chunkOnlyConfig = {
- assets: false,
- cached: false,
- children: false,
- chunks: true,
- chunkModules: false,
- chunkOrigins: false,
- errorDetails: false,
- hash: false,
- modules: false,
- reasons: false,
- source: false,
- timings: false,
- version: false
- };
- const allChunks = compilation.getStats().toJson(chunkOnlyConfig).chunks;
-
- let chunks = self.filterChunks(allChunks, self.options.chunks, self.options.excludeChunks);
-
- chunks = self.sortChunks(chunks, self.options.chunksSortMode, compilation);
-
- if (compilation.hooks) {
- chunks = compilation.hooks.htmlWebpackPluginAlterChunks.call(chunks, { plugin: self });
- } else {
-
- chunks = compilation.applyPluginsWaterfall('html-webpack-plugin-alter-chunks', chunks, { plugin: self });
- }
-
- const assets = self.htmlWebpackPluginAssets(compilation, chunks);
-
-
-
- if (self.isHotUpdateCompilation(assets)) {
- return callback();
- }
-
- const assetJson = JSON.stringify(self.getAssetFiles(assets));
- if (isCompilationCached && self.options.cache && assetJson === self.assetJson) {
- return callback();
- } else {
- self.assetJson = assetJson;
- }
- Promise.resolve()
-
- .then(() => {
- if (self.options.favicon) {
- return self.addFileToAssets(self.options.favicon, compilation)
- .then(faviconBasename => {
- let publicPath = compilation.mainTemplate.getPublicPath({hash: compilation.hash}) || '';
- if (publicPath && publicPath.substr(-1) !== '/') {
- publicPath += '/';
- }
- assets.favicon = publicPath + faviconBasename;
- });
- }
- })
-
- .then(() => compilationPromise)
- .then(compiledTemplate => {
-
- if (self.options.templateContent !== undefined) {
- return self.options.templateContent;
- }
-
-
- return self.evaluateCompilationResult(compilation, compiledTemplate);
- })
-
-
- .then(compilationResult => applyPluginsAsyncWaterfall('html-webpack-plugin-before-html-generation', false, {
- assets: assets,
- outputName: self.childCompilationOutputName,
- plugin: self
- })
- .then(() => compilationResult))
-
- .then(compilationResult => typeof compilationResult !== 'function'
- ? compilationResult
- : self.executeTemplate(compilationResult, chunks, assets, compilation))
-
- .then(html => {
- const pluginArgs = {html: html, assets: assets, plugin: self, outputName: self.childCompilationOutputName};
- return applyPluginsAsyncWaterfall('html-webpack-plugin-before-html-processing', true, pluginArgs);
- })
- .then(result => {
- const html = result.html;
- const assets = result.assets;
-
- const assetTags = self.generateHtmlTags(assets);
- const 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(result => self.postProcessHtml(html, assets, { body: result.body, head: result.head })
- .then(html => _.extend(result, {html: html, assets: assets})));
- })
-
- .then(result => {
- const html = result.html;
- const assets = result.assets;
- const pluginArgs = {html: html, assets: assets, plugin: self, outputName: self.childCompilationOutputName};
- return applyPluginsAsyncWaterfall('html-webpack-plugin-after-html-processing', true, pluginArgs)
- .then(result => result.html);
- })
- .catch(err => {
-
-
- compilation.errors.push(prettyError(err, compiler.context).toString());
-
- self.hash = null;
- return self.options.showErrors ? prettyError(err, compiler.context).toHtml() : 'ERROR';
- })
- .then(html => {
-
- compilation.assets[self.childCompilationOutputName] = {
- source: () => html,
- size: () => html.length
- };
- })
- .then(() => applyPluginsAsyncWaterfall('html-webpack-plugin-after-emit', false, {
- html: compilation.assets[self.childCompilationOutputName],
- outputName: self.childCompilationOutputName,
- plugin: self
- }).catch(err => {
- console.error(err);
- return null;
- }).then(() => null))
-
- .then(() => {
- callback();
- });
- });
- }
-
- evaluateCompilationResult (compilation, source) {
- if (!source) {
- return Promise.reject('The child compilation didn\'t provide a result');
- }
-
-
- source = source.replace('var HTML_WEBPACK_PLUGIN_RESULT =', '');
- const template = this.options.template.replace(/^.+!/, '').replace(/\?.+$/, '');
- const vmContext = vm.createContext(_.extend({HTML_WEBPACK_PLUGIN: true, require: require}, global));
- const vmScript = new vm.Script(source, {filename: template});
-
- let 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.');
- }
-
- getTemplateParameters (compilation, assets) {
- if (typeof this.options.templateParameters === 'function') {
- return this.options.templateParameters(compilation, assets, this.options);
- }
- if (typeof this.options.templateParameters === 'object') {
- return this.options.templateParameters;
- }
- return {};
- }
-
- executeTemplate (templateFunction, chunks, assets, compilation) {
- return Promise.resolve()
-
- .then(() => {
- const templateParams = this.getTemplateParameters(compilation, assets);
- let html = '';
- try {
- html = templateFunction(templateParams);
- } catch (e) {
- compilation.errors.push(new Error('Template execution failed: ' + e));
- return Promise.reject(e);
- }
- return html;
- });
- }
-
- postProcessHtml (html, assets, assetTags) {
- const self = this;
- if (typeof html !== 'string') {
- return Promise.reject('Expected html to be a string but got ' + JSON.stringify(html));
- }
- return Promise.resolve()
-
- .then(() => {
- if (self.options.inject) {
- return self.injectAssetsIntoHtml(html, assets, assetTags);
- } else {
- return html;
- }
- })
-
- .then(html => {
- if (self.options.minify) {
- const minify = require('html-minifier').minify;
- return minify(html, self.options.minify);
- }
- return html;
- });
- }
-
- addFileToAssets (filename, compilation) {
- filename = path.resolve(compilation.compiler.context, filename);
- return Promise.all([
- fsStatAsync(filename),
- fsReadFileAsync(filename)
- ])
- .then(([size, source]) => {
- return {
- size,
- source
- };
- })
- .catch(() => Promise.reject(new Error('HtmlWebpackPlugin: could not load file ' + filename)))
- .then(results => {
- const basename = path.basename(filename);
- if (compilation.fileDependencies.add) {
- compilation.fileDependencies.add(filename);
- } else {
-
- compilation.fileDependencies.push(filename);
- }
- compilation.assets[basename] = {
- source: () => results.source,
- size: () => results.size.size
- };
- return basename;
- });
- }
-
- sortChunks (chunks, sortMode, compilation) {
-
- if (typeof sortMode === 'function') {
- return chunks.sort(sortMode);
- }
-
- if (typeof chunkSorter[sortMode] !== 'undefined') {
- return chunkSorter[sortMode](chunks, this.options, compilation);
- }
- throw new Error('"' + sortMode + '" is not a valid chunk sort mode');
- }
-
- filterChunks (chunks, includedChunks, excludedChunks) {
- return chunks.filter(chunk => {
- const 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;
- });
- }
- isHotUpdateCompilation (assets) {
- return assets.js.length && assets.js.every(name => /\.hot-update\.js$/.test(name));
- }
- htmlWebpackPluginAssets (compilation, chunks) {
- const self = this;
- const compilationHash = compilation.hash;
-
- let 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 += '/';
- }
- const assets = {
-
- publicPath: publicPath,
-
- chunks: {},
-
- js: [],
-
- css: [],
-
- manifest: Object.keys(compilation.assets).filter(assetFile => path.extname(assetFile) === '.appcache')[0]
- };
-
- if (this.options.hash) {
- assets.manifest = self.appendHash(assets.manifest, compilationHash);
- assets.favicon = self.appendHash(assets.favicon, compilationHash);
- }
- for (let i = 0; i < chunks.length; i++) {
- const chunk = chunks[i];
- const chunkName = chunk.names[0];
- assets.chunks[chunkName] = {};
-
- let chunkFiles = [].concat(chunk.files).map(chunkFile => publicPath + chunkFile);
-
- if (this.options.hash) {
- chunkFiles = chunkFiles.map(chunkFile => self.appendHash(chunkFile, compilationHash));
- }
-
-
- const js = chunkFiles.find(chunkFile => /.js($|\?)/.test(chunkFile));
- if (js) {
- assets.chunks[chunkName].size = chunk.size;
- assets.chunks[chunkName].entry = js;
- assets.chunks[chunkName].hash = chunk.hash;
- assets.js.push(js);
- }
-
- const css = chunkFiles.filter(chunkFile => /.css($|\?)/.test(chunkFile));
- assets.chunks[chunkName].css = css;
- assets.css = assets.css.concat(css);
- }
-
-
- assets.css = _.uniq(assets.css);
- return assets;
- }
-
- getMetaTags () {
- if (this.options.meta === false) {
- return [];
- }
-
-
-
- const selfClosingTag = !!this.options.xhtml;
- const metaTagAttributeObjects = Object.keys(this.options.meta).map((metaName) => {
- const metaTagContent = this.options.meta[metaName];
- return (typeof metaTagContent === 'object') ? metaTagContent : {
- name: metaName,
- content: metaTagContent
- };
- });
-
-
- return metaTagAttributeObjects.map((metaTagAttributes) => {
- return {
- tagName: 'meta',
- voidTag: true,
- selfClosingTag: selfClosingTag,
- attributes: metaTagAttributes
- };
- });
- }
-
- generateHtmlTags (assets) {
-
- const scripts = assets.js.map(scriptPath => ({
- tagName: 'script',
- closeTag: true,
- attributes: {
- type: 'text/javascript',
- src: scriptPath
- }
- }));
-
- const selfClosingTag = !!this.options.xhtml;
-
- const styles = assets.css.map(stylePath => ({
- tagName: 'link',
- selfClosingTag: selfClosingTag,
- voidTag: true,
- attributes: {
- href: stylePath,
- rel: 'stylesheet'
- }
- }));
-
- let head = this.getMetaTags();
- let body = [];
-
- if (assets.favicon) {
- head.push({
- tagName: 'link',
- selfClosingTag: selfClosingTag,
- voidTag: true,
- 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};
- }
-
- injectAssetsIntoHtml (html, assets, assetTags) {
- const htmlRegExp = /(<html[^>]*>)/i;
- const headRegExp = /(<\/head\s*>)/i;
- const bodyRegExp = /(<\/body\s*>)/i;
- const body = assetTags.body.map(this.createHtmlTag.bind(this));
- const head = assetTags.head.map(this.createHtmlTag.bind(this));
- if (body.length) {
- if (bodyRegExp.test(html)) {
-
- html = html.replace(bodyRegExp, match => 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, match => match + '<head></head>');
- }
- }
-
- html = html.replace(headRegExp, match => head.join('') + match);
- }
-
- if (assets.manifest) {
- html = html.replace(/(<html[^>]*)(>)/i, (match, start, end) => {
-
- if (/\smanifest\s*=/.test(match)) {
- return match;
- }
- return start + ' manifest="' + assets.manifest + '"' + end;
- });
- }
- return html;
- }
-
- appendHash (url, hash) {
- if (!url) {
- return url;
- }
- return url + (url.indexOf('?') === -1 ? '?' : '&') + hash;
- }
-
- createHtmlTag (tagDefinition) {
- const attributes = Object.keys(tagDefinition.attributes || {})
- .filter(attributeName => tagDefinition.attributes[attributeName] !== false)
- .map(attributeName => {
- if (tagDefinition.attributes[attributeName] === true) {
- return attributeName;
- }
- return attributeName + '="' + tagDefinition.attributes[attributeName] + '"';
- });
-
- const voidTag = tagDefinition.voidTag !== undefined ? tagDefinition.voidTag : !tagDefinition.closeTag;
- const selfClosingTag = tagDefinition.voidTag !== undefined ? tagDefinition.voidTag && this.options.xhtml : tagDefinition.selfClosingTag;
- return '<' + [tagDefinition.tagName].concat(attributes).join(' ') + (selfClosingTag ? '/' : '') + '>' +
- (tagDefinition.innerHTML || '') +
- (voidTag ? '' : '</' + tagDefinition.tagName + '>');
- }
-
- getFullTemplatePath (template, context) {
-
- if (template.indexOf('!') === -1) {
- template = require.resolve('./lib/loader.js') + '!' + path.resolve(context, template);
- }
-
- return template.replace(
- /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/,
- (match, prefix, filepath, postfix) => prefix + path.resolve(filepath) + postfix);
- }
-
- getAssetFiles (assets) {
- const files = _.uniq(Object.keys(assets).filter(assetType => assetType !== 'chunks' && assets[assetType]).reduce((files, assetType) => files.concat(assets[assetType]), []));
- files.sort();
- return files;
- }
-
- applyPluginsAsyncWaterfall (compilation) {
- if (compilation.hooks) {
- return (eventName, requiresResult, pluginArgs) => {
- const ccEventName = trainCaseToCamelCase(eventName);
- if (!compilation.hooks[ccEventName]) {
- compilation.errors.push(
- new Error('No hook found for ' + eventName)
- );
- }
- return compilation.hooks[ccEventName].promise(pluginArgs);
- };
- }
-
- const promisedApplyPluginsAsyncWaterfall = function (name, init) {
- return new Promise((resolve, reject) => {
- const callback = function (err, result) {
- if (err) {
- return reject(err);
- }
- resolve(result);
- };
- compilation.applyPluginsAsyncWaterfall(name, init, callback);
- });
- };
- return (eventName, requiresResult, pluginArgs) => promisedApplyPluginsAsyncWaterfall(eventName, pluginArgs)
- .then(result => {
- if (requiresResult && !result) {
- compilation.warnings.push(
- new Error('Using ' + eventName + ' without returning a result is deprecated.')
- );
- }
- return _.extend(pluginArgs, result);
- });
- }
- }
- function trainCaseToCamelCase (word) {
- return word.replace(/-([\w])/g, (match, p1) => p1.toUpperCase());
- }
- function templateParametersGenerator (compilation, assets, options) {
- return {
- compilation: compilation,
- webpack: compilation.getStats().toJson(),
- webpackConfig: compilation.options,
- htmlWebpackPlugin: {
- files: assets,
- options: options
- }
- };
- }
- module.exports = HtmlWebpackPlugin;
|