diff --git a/.node-version b/.node-version new file mode 100644 index 000000000..a00377650 --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +6.11.5 diff --git a/CHANGELOG.md b/CHANGELOG.md index 25d1d2d47..87a6e7245 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ Change History ============== +v3.0.0 +--- +* Add support for the new [https://github.com/webpack/tapable](webpack tapable) to be compatible with webpack 4.x +* Similar to webpack 4.x the support for node versions older than 6 are no longer supported +* Remove bluebird dependency + v2.30.1 --- * Revert part the performance optimization (#723) because of #753. diff --git a/index.js b/index.js index 141d3a0d8..a82429db8 100644 --- a/index.js +++ b/index.js @@ -1,702 +1,657 @@ '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) { - // Default 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; +// use Polyfill for util.promisify in node versions < v8 +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) { + // Default 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); + } - this.options.template = this.getFullTemplatePath(this.options.template, compiler.context); + apply (compiler) { + const self = this; + let isCompilationCached = false; + let compilationPromise; - // convert absolute filename into relative so that webpack can - // generate it at correct location - var filename = this.options.filename; - if (path.resolve(filename) === path.normalize(filename)) { - this.options.filename = path.relative(compiler.options.output.path, filename); - } + this.options.template = this.getFullTemplatePath(this.options.template, compiler.context); - // setup hooks for webpack 4 - if (compiler.hooks) { - compiler.hooks.compilation.tap('HtmlWebpackPluginHooks', function (compilation) { - var SyncWaterfallHook = require('tapable').SyncWaterfallHook; - var 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']); - }); - } + // convert absolute filename into relative so that webpack can + // generate it at correct location + const 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) { - // Compile the template (queued) - 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) { - // If the compilation change didnt change the cache is valid - isCompilationCached = compilationResult.hash && self.childCompilerHash === compilationResult.hash; - self.childCompilerHash = compilationResult.hash; - self.childCompilationOutputName = compilationResult.outputName; - callback(); - return compilationResult.content; + // setup hooks for webpack 4 + 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.plugin('emit', function (compilation, callback) { - var applyPluginsAsyncWaterfall = self.applyPluginsAsyncWaterfall(compilation); - // Get all chunks - var allChunks = compilation.getStats().toJson().chunks; - // Filter chunks (options.chunks and options.excludeCHunks) - var chunks = self.filterChunks(allChunks, self.options.chunks, self.options.excludeChunks); - // Sort chunks - chunks = self.sortChunks(chunks, self.options.chunksSortMode, compilation.chunkGroups); - // Let plugins alter the chunks and the chunk sorting - if (compilation.hooks) { - chunks = compilation.hooks.htmlWebpackPluginAlterChunks.call(chunks, { plugin: self }); - } else { - // Before Webpack 4 - chunks = compilation.applyPluginsWaterfall('html-webpack-plugin-alter-chunks', chunks, { plugin: self }); - } - // Get assets - var assets = self.htmlWebpackPluginAssets(compilation, chunks); - // If this is a hot update compilation, move on! - // This solves a problem where an `index.html` file is generated for hot-update js files - // It only happens in Webpack 2, where hot updates are emitted separately before the full bundle - if (self.isHotUpdateCompilation(assets)) { - return callback(); } - // If the template and the assets did not change we don't have to emit the html - var assetJson = JSON.stringify(self.getAssetFiles(assets)); - if (isCompilationCached && self.options.cache && assetJson === self.assetJson) { - return callback(); - } else { - self.assetJson = assetJson; - } + compiler.plugin('make', (compilation, callback) => { + // Compile the template (queued) + 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 => { + // If the compilation change didnt change the cache is valid + isCompilationCached = compilationResult.hash && self.childCompilerHash === compilationResult.hash; + self.childCompilerHash = compilationResult.hash; + self.childCompilationOutputName = compilationResult.outputName; + callback(); + return compilationResult.content; + }); + }); - Promise.resolve() - // Favicon - .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; - }); - } - }) - // Wait for the compilation to finish - .then(function () { - return compilationPromise; - }) - .then(function (compiledTemplate) { - // Allow to use a custom function / string instead - if (self.options.templateContent !== undefined) { - return self.options.templateContent; - } - // Once everything is compiled evaluate the html factory - // and replace it with its content - return self.evaluateCompilationResult(compilation, compiledTemplate); - }) - // Allow plugins to make changes to the assets before invoking the template - // This only makes sense to use if `inject` is `false` - .then(function (compilationResult) { - return applyPluginsAsyncWaterfall('html-webpack-plugin-before-html-generation', false, { + compiler.plugin('emit', (compilation, callback) => { + const applyPluginsAsyncWaterfall = self.applyPluginsAsyncWaterfall(compilation); + // Get all chunks + const allChunks = compilation.getStats().toJson().chunks; + // Filter chunks (options.chunks and options.excludeCHunks) + let chunks = self.filterChunks(allChunks, self.options.chunks, self.options.excludeChunks); + // Sort chunks + chunks = self.sortChunks(chunks, self.options.chunksSortMode, compilation.chunkGroups); + // Let plugins alter the chunks and the chunk sorting + if (compilation.hooks) { + chunks = compilation.hooks.htmlWebpackPluginAlterChunks.call(chunks, { plugin: self }); + } else { + // Before Webpack 4 + chunks = compilation.applyPluginsWaterfall('html-webpack-plugin-alter-chunks', chunks, { plugin: self }); + } + // Get assets + const assets = self.htmlWebpackPluginAssets(compilation, chunks); + // If this is a hot update compilation, move on! + // This solves a problem where an `index.html` file is generated for hot-update js files + // It only happens in Webpack 2, where hot updates are emitted separately before the full bundle + if (self.isHotUpdateCompilation(assets)) { + return callback(); + } + + // If the template and the assets did not change we don't have to emit the html + const assetJson = JSON.stringify(self.getAssetFiles(assets)); + if (isCompilationCached && self.options.cache && assetJson === self.assetJson) { + return callback(); + } else { + self.assetJson = assetJson; + } + + Promise.resolve() + // Favicon + .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; + }); + } + }) + // Wait for the compilation to finish + .then(() => compilationPromise) + .then(compiledTemplate => { + // Allow to use a custom function / string instead + if (self.options.templateContent !== undefined) { + return self.options.templateContent; + } + // Once everything is compiled evaluate the html factory + // and replace it with its content + return self.evaluateCompilationResult(compilation, compiledTemplate); + }) + // Allow plugins to make changes to the assets before invoking the template + // This only makes sense to use if `inject` is `false` + .then(compilationResult => applyPluginsAsyncWaterfall('html-webpack-plugin-before-html-generation', false, { assets: assets, outputName: self.childCompilationOutputName, plugin: self }) - .then(function () { - return compilationResult; - }); - }) - // Execute the template - .then(function (compilationResult) { - // If the loader result is a function execute it to retrieve the html - // otherwise use the returned html - return typeof compilationResult !== 'function' - ? compilationResult - : self.executeTemplate(compilationResult, chunks, assets, compilation); - }) - // Allow plugins to change the html before assets are injected - .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; - // Prepare script and link tags - var assetTags = self.generateAssetTags(assets); - var pluginArgs = {head: assetTags.head, body: assetTags.body, plugin: self, chunks: chunks, outputName: self.childCompilationOutputName}; - // Allow plugins to change the assetTag definitions - return applyPluginsAsyncWaterfall('html-webpack-plugin-alter-asset-tags', true, pluginArgs) - .then(function (result) { - // Add the stylesheets, scripts and so on to the resulting html - return self.postProcessHtml(html, assets, { body: result.body, head: result.head }) - .then(function (html) { - return _.extend(result, {html: html, assets: assets}); - }); - }); - }) - // Allow plugins to change the html after assets are injected - .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) { - // In case anything went wrong the promise is resolved - // with the error message and an error is logged - compilation.errors.push(prettyError(err, compiler.context).toString()); - // Prevent caching - self.hash = null; - return self.options.showErrors ? prettyError(err, compiler.context).toHtml() : 'ERROR'; - }) - .then(function (html) { - // Replace the compilation result with the evaluated html code - compilation.assets[self.childCompilationOutputName] = { - source: function () { - return html; - }, - size: function () { - return html.length; - } - }; - }) - .then(function () { - // Let other plugins know that we are done: - return applyPluginsAsyncWaterfall('html-webpack-plugin-after-emit', false, { + .then(() => compilationResult)) + // Execute the template + .then(compilationResult => typeof compilationResult !== 'function' + ? compilationResult + : self.executeTemplate(compilationResult, chunks, assets, compilation)) + // Allow plugins to change the html before assets are injected + .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; + // Prepare script and link tags + const assetTags = self.generateAssetTags(assets); + const pluginArgs = {head: assetTags.head, body: assetTags.body, plugin: self, chunks: chunks, outputName: self.childCompilationOutputName}; + // Allow plugins to change the assetTag definitions + 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}))); + }) + // Allow plugins to change the html after assets are injected + .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 => { + // In case anything went wrong the promise is resolved + // with the error message and an error is logged + compilation.errors.push(prettyError(err, compiler.context).toString()); + // Prevent caching + self.hash = null; + return self.options.showErrors ? prettyError(err, compiler.context).toHtml() : 'ERROR'; + }) + .then(html => { + // Replace the compilation result with the evaluated html code + 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(function (err) { + }).catch(err => { console.error(err); return null; - }).then(function () { - return null; + }).then(() => null)) + // Let webpack continue with it + .then(() => { + callback(); }); - }) - // Let webpack continue with it - .finally(function () { - callback(); - // Tell blue bird that we don't want to wait for callback. - // Fixes "Warning: a promise was created in a handler but none were returned from it" - // https://github.com/petkaantonov/bluebird/blob/master/docs/docs/warning-explanations.md#warning-a-promise-was-created-in-a-handler-but-none-were-returned-from-it - return null; - }); - }); -}; - -/** - * Evaluates the child compilation result - * Returns a promise - */ -HtmlWebpackPlugin.prototype.evaluateCompilationResult = function (compilation, source) { - if (!source) { - return Promise.reject('The child compilation didn\'t provide a result'); + }); } - // The LibraryTemplatePlugin stores the template result in a local variable. - // To extract the result during the evaluation this part has to be removed. - 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}); - // Evaluate code and cast to string - var newSource; - try { - newSource = vmScript.runInContext(vmContext); - } catch (e) { - return Promise.reject(e); - } - if (typeof newSource === 'object' && newSource.__esModule && newSource.default) { - newSource = newSource.default; + /** + * Evaluates the child compilation result + * Returns a promise + */ + evaluateCompilationResult (compilation, source) { + if (!source) { + return Promise.reject('The child compilation didn\'t provide a result'); + } + + // The LibraryTemplatePlugin stores the template result in a local variable. + // To extract the result during the evaluation this part has to be removed. + 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}); + // Evaluate code and cast to string + 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.'); } - return typeof newSource === 'string' || typeof newSource === 'function' - ? Promise.resolve(newSource) - : Promise.reject('The loader "' + this.options.template + '" didn\'t return html.'); -}; -/** - * Html post processing - * - * Returns a promise - */ -HtmlWebpackPlugin.prototype.executeTemplate = function (templateFunction, chunks, assets, compilation) { - var self = this; - return Promise.resolve() - // Template processing - .then(function () { - var templateParams = { - compilation: compilation, - webpack: compilation.getStats().toJson(), - webpackConfig: compilation.options, - htmlWebpackPlugin: { - files: assets, - options: self.options + /** + * Html post processing + * + * Returns a promise + */ + executeTemplate (templateFunction, chunks, assets, compilation) { + const self = this; + return Promise.resolve() + // Template processing + .then(() => { + const templateParams = { + compilation: compilation, + webpack: compilation.getStats().toJson(), + webpackConfig: compilation.options, + htmlWebpackPlugin: { + files: assets, + options: self.options + } + }; + let html = ''; + try { + html = templateFunction(templateParams); + } catch (e) { + compilation.errors.push(new Error('Template execution failed: ' + e)); + return Promise.reject(e); } - }; - var html = ''; - try { - html = templateFunction(templateParams); - } catch (e) { - compilation.errors.push(new Error('Template execution failed: ' + e)); - return Promise.reject(e); - } - return html; - }); -}; - -/** - * Html post processing - * - * Returns a promise - */ -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 html; + }); } - return Promise.resolve() - // Inject - .then(function () { - if (self.options.inject) { - return self.injectAssetsIntoHtml(html, assets, assetTags); - } else { + + /** + * Html post processing + * + * Returns a promise + */ + 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() + // Inject + .then(() => { + if (self.options.inject) { + return self.injectAssetsIntoHtml(html, assets, assetTags); + } else { + return html; + } + }) + // Minify + .then(html => { + if (self.options.minify) { + const minify = require('html-minifier').minify; + return minify(html, self.options.minify); + } return html; - } + }); + } + + /* + * Pushes the content of the given filename to the compilation assets + */ + addFileToAssets (filename, compilation) { + filename = path.resolve(compilation.compiler.context, filename); + return Promise.all([ + fsStatAsync(filename), + fsReadFileAsync(filename) + ]) + .then(([size, source]) => { + return { + size, + source + }; }) - // Minify - .then(function (html) { - if (self.options.minify) { - var minify = require('html-minifier').minify; - return minify(html, self.options.minify); + .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 { + // Before Webpack 4 - fileDepenencies was an array + compilation.fileDependencies.push(filename); } - return html; + compilation.assets[basename] = { + source: () => results.source, + size: () => results.size.size + }; + return basename; }); -}; - -/* - * Pushes the content of the given filename to the compilation assets - */ -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); - if (compilation.fileDependencies.add) { - compilation.fileDependencies.add(filename); - } else { - // Before Webpack 4 - fileDepenencies was an array - compilation.fileDependencies.push(filename); - } - compilation.assets[basename] = { - source: function () { - return results.source; - }, - size: function () { - return results.size.size; - } - }; - return basename; - }); -}; - -/** - * Helper to sort chunks - */ -HtmlWebpackPlugin.prototype.sortChunks = function (chunks, sortMode, chunkGroups) { - // Sort mode auto by default: - if (typeof sortMode === 'undefined') { - sortMode = 'auto'; } - // Custom function - if (typeof sortMode === 'function') { - return chunks.sort(sortMode); - } - // Disabled sorting: - if (sortMode === 'none') { - return chunkSorter.none(chunks); - } - if (sortMode === 'manual') { - return chunkSorter.manual(chunks, this.options.chunks); - } - // Check if the given sort mode is a valid chunkSorter sort mode - if (typeof chunkSorter[sortMode] !== 'undefined') { - return chunkSorter[sortMode](chunks, chunkGroups); - } - throw new Error('"' + sortMode + '" is not a valid chunk sort mode'); -}; -/** - * Return all chunks from the compilation result which match the exclude and include filters - */ -HtmlWebpackPlugin.prototype.filterChunks = function (chunks, includedChunks, excludedChunks) { - return chunks.filter(function (chunk) { - var chunkName = chunk.names[0]; - // This chunk doesn't have a name. This script can't handled it. - if (chunkName === undefined) { - return false; + /** + * Helper to sort chunks + */ + sortChunks (chunks, sortMode, chunkGroups) { + // Sort mode auto by default: + if (typeof sortMode === 'undefined') { + sortMode = 'auto'; } - // Skip if the chunk should be lazy loaded - if (typeof chunk.isInitial === 'function') { - if (!chunk.isInitial()) { - return false; - } - } else if (!chunk.initial) { - return false; + // Custom function + if (typeof sortMode === 'function') { + return chunks.sort(sortMode); + } + // Disabled sorting: + if (sortMode === 'none') { + return chunkSorter.none(chunks); } - // Skip if the chunks should be filtered and the given chunk was not added explicity - if (Array.isArray(includedChunks) && includedChunks.indexOf(chunkName) === -1) { - return false; + if (sortMode === 'manual') { + return chunkSorter.manual(chunks, this.options.chunks); } - // Skip if the chunks should be filtered and the given chunk was excluded explicity - if (Array.isArray(excludedChunks) && excludedChunks.indexOf(chunkName) !== -1) { - return false; + // Check if the given sort mode is a valid chunkSorter sort mode + if (typeof chunkSorter[sortMode] !== 'undefined') { + return chunkSorter[sortMode](chunks, chunkGroups); } - // Add otherwise - 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; - - // Use the configured public path or build a relative path - var publicPath = typeof compilation.options.output.publicPath !== 'undefined' - // If a hard coded public path exists use it - ? compilation.mainTemplate.getPublicPath({hash: compilationHash}) - // If no public path was set get a relative url path - : 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 += '/'; + throw new Error('"' + sortMode + '" is not a valid chunk sort mode'); } - var assets = { - // The public path - publicPath: publicPath, - // Will contain all js & css files by chunk - chunks: {}, - // Will contain all js files - js: [], - // Will contain all css files - css: [], - // Will contain the html5 appcache manifest files if it exists - manifest: Object.keys(compilation.assets).filter(function (assetFile) { - return path.extname(assetFile) === '.appcache'; - })[0] - }; - - // Append a hash for cache busting - if (this.options.hash) { - assets.manifest = self.appendHash(assets.manifest, compilationHash); - assets.favicon = self.appendHash(assets.favicon, compilationHash); + /** + * Return all chunks from the compilation result which match the exclude and include filters + */ + filterChunks (chunks, includedChunks, excludedChunks) { + return chunks.filter(chunk => { + const chunkName = chunk.names[0]; + // This chunk doesn't have a name. This script can't handled it. + if (chunkName === undefined) { + return false; + } + // Skip if the chunk should be lazy loaded + if (typeof chunk.isInitial === 'function') { + if (!chunk.isInitial()) { + return false; + } + } else if (!chunk.initial) { + return false; + } + // Skip if the chunks should be filtered and the given chunk was not added explicity + if (Array.isArray(includedChunks) && includedChunks.indexOf(chunkName) === -1) { + return false; + } + // Skip if the chunks should be filtered and the given chunk was excluded explicity + if (Array.isArray(excludedChunks) && excludedChunks.indexOf(chunkName) !== -1) { + return false; + } + // Add otherwise + return true; + }); } - for (var i = 0; i < chunks.length; i++) { - var chunk = chunks[i]; - var chunkName = chunk.names[0]; + isHotUpdateCompilation (assets) { + return assets.js.length && assets.js.every(name => /\.hot-update\.js$/.test(name)); + } - assets.chunks[chunkName] = {}; + htmlWebpackPluginAssets (compilation, chunks) { + const self = this; + const compilationHash = compilation.hash; - // Prepend the public path to all chunk files - var chunkFiles = [].concat(chunk.files).map(function (chunkFile) { - return publicPath + chunkFile; - }); + // Use the configured public path or build a relative path + let publicPath = typeof compilation.options.output.publicPath !== 'undefined' + // If a hard coded public path exists use it + ? compilation.mainTemplate.getPublicPath({hash: compilationHash}) + // If no public path was set get a relative url path + : 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 = { + // The public path + publicPath: publicPath, + // Will contain all js & css files by chunk + chunks: {}, + // Will contain all js files + js: [], + // Will contain all css files + css: [], + // Will contain the html5 appcache manifest files if it exists + manifest: Object.keys(compilation.assets).filter(assetFile => path.extname(assetFile) === '.appcache')[0] + }; // Append a hash for cache busting if (this.options.hash) { - chunkFiles = chunkFiles.map(function (chunkFile) { - return self.appendHash(chunkFile, compilationHash); - }); + assets.manifest = self.appendHash(assets.manifest, compilationHash); + assets.favicon = self.appendHash(assets.favicon, compilationHash); } - // Webpack outputs an array for each chunk when using sourcemaps - // But we need only the entry file - 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); - - // Gather all css files - var css = chunkFiles.filter(function (chunkFile) { - // Some chunks may contain content hash in their names, for ex. 'main.css?1e7cac4e4d8b52fd5ccd2541146ef03f'. - // We must proper handle such cases, so we use regexp testing here - return /.css($|\?)/.test(chunkFile); - }); - assets.chunks[chunkName].css = css; - assets.css = assets.css.concat(css); - } + for (let i = 0; i < chunks.length; i++) { + const chunk = chunks[i]; + const chunkName = chunk.names[0]; - // Duplicate css assets can occur on occasion if more than one chunk - // requires the same css. - assets.css = _.uniq(assets.css); + assets.chunks[chunkName] = {}; - return assets; -}; + // Prepend the public path to all chunk files + let chunkFiles = [].concat(chunk.files).map(chunkFile => publicPath + chunkFile); -/** - * Injects the assets into the given html string - */ -HtmlWebpackPlugin.prototype.generateAssetTags = function (assets) { - // Turn script files into script tags - var scripts = assets.js.map(function (scriptPath) { - return { + // Append a hash for cache busting + if (this.options.hash) { + chunkFiles = chunkFiles.map(chunkFile => self.appendHash(chunkFile, compilationHash)); + } + + // Webpack outputs an array for each chunk when using sourcemaps + // But we need only the entry file + const entry = chunkFiles[0]; + assets.chunks[chunkName].size = chunk.size; + assets.chunks[chunkName].entry = entry; + assets.chunks[chunkName].hash = chunk.hash; + assets.js.push(entry); + + // Gather all css files + const css = chunkFiles.filter(chunkFile => /.css($|\?)/.test(chunkFile)); + assets.chunks[chunkName].css = css; + assets.css = assets.css.concat(css); + } + + // Duplicate css assets can occur on occasion if more than one chunk + // requires the same css. + assets.css = _.uniq(assets.css); + + return assets; + } + + /** + * Injects the assets into the given html string + */ + generateAssetTags (assets) { + // Turn script files into script tags + const scripts = assets.js.map(scriptPath => ({ tagName: 'script', closeTag: true, + attributes: { type: 'text/javascript', src: scriptPath } - }; - }); - // Make tags self-closing in case of xhtml - var selfClosingTag = !!this.options.xhtml; - // Turn css files into link tags - var styles = assets.css.map(function (stylePath) { - return { + })); + // Make tags self-closing in case of xhtml + const selfClosingTag = !!this.options.xhtml; + // Turn css files into link tags + const styles = assets.css.map(stylePath => ({ tagName: 'link', selfClosingTag: selfClosingTag, + attributes: { href: stylePath, rel: 'stylesheet' } - }; - }); - // Injection targets - var head = []; - var body = []; - - // If there is a favicon present, add it to the head - if (assets.favicon) { - head.push({ - tagName: 'link', - selfClosingTag: selfClosingTag, - attributes: { - rel: 'shortcut icon', - href: assets.favicon - } - }); - } - // Add styles to the head - head = head.concat(styles); - // Add scripts to body or head - if (this.options.inject === 'head') { - head = head.concat(scripts); - } else { - body = body.concat(scripts); - } - return {head: head, body: body}; -}; - -/** - * Injects the assets into the given html string - */ -HtmlWebpackPlugin.prototype.injectAssetsIntoHtml = function (html, assets, assetTags) { - var htmlRegExp = /(]*>)/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)) { - // Append assets to body element - html = html.replace(bodyRegExp, function (match) { - return body.join('') + match; + })); + // Injection targets + let head = []; + let body = []; + + // If there is a favicon present, add it to the head + if (assets.favicon) { + head.push({ + tagName: 'link', + selfClosingTag: selfClosingTag, + attributes: { + rel: 'shortcut icon', + href: assets.favicon + } }); + } + // Add styles to the head + head = head.concat(styles); + // Add scripts to body or head + if (this.options.inject === 'head') { + head = head.concat(scripts); } else { - // Append scripts to the end of the file if no element exists: - html += body.join(''); + body = body.concat(scripts); } + return {head: head, body: body}; } - if (head.length) { - // Create a head tag if none exists - if (!headRegExp.test(html)) { - if (!htmlRegExp.test(html)) { - html = ' ' + html; + /** + * Injects the assets into the given html string + */ + injectAssetsIntoHtml (html, assets, assetTags) { + const htmlRegExp = /(]*>)/i; + const headRegExp = /(<\/head\s*>)/i; + const bodyRegExp = /(<\/body\s*>)/i; + const body = assetTags.body.map(this.createHtmlTag); + const head = assetTags.head.map(this.createHtmlTag); + + if (body.length) { + if (bodyRegExp.test(html)) { + // Append assets to body element + html = html.replace(bodyRegExp, match => body.join('') + match); } else { - html = html.replace(htmlRegExp, function (match) { - return match + ' '; - }); + // Append scripts to the end of the file if no element exists: + html += body.join(''); } } - // Append assets to head element - html = html.replace(headRegExp, function (match) { - return head.join('') + match; - }); + if (head.length) { + // Create a head tag if none exists + if (!headRegExp.test(html)) { + if (!htmlRegExp.test(html)) { + html = ' ' + html; + } else { + html = html.replace(htmlRegExp, match => match + ' '); + } + } + + // Append assets to head element + html = html.replace(headRegExp, match => head.join('') + match); + } + + // Inject manifest into the opening html tag + if (assets.manifest) { + html = html.replace(/(]*)(>)/i, (match, start, end) => { + // Append the manifest only if no manifest was specified + if (/\smanifest\s*=/.test(match)) { + return match; + } + return start + ' manifest="' + assets.manifest + '"' + end; + }); + } + return html; } - // Inject manifest into the opening html tag - if (assets.manifest) { - html = html.replace(/(]*)(>)/i, function (match, start, end) { - // Append the manifest only if no manifest was specified - if (/\smanifest\s*=/.test(match)) { - return match; - } - return start + ' manifest="' + assets.manifest + '"' + end; - }); + /** + * Appends a cache busting hash + */ + appendHash (url, hash) { + if (!url) { + return url; + } + return url + (url.indexOf('?') === -1 ? '?' : '&') + hash; } - return html; -}; -/** - * Appends a cache busting hash - */ -HtmlWebpackPlugin.prototype.appendHash = function (url, hash) { - if (!url) { - return url; + /** + * Turn a tag definition into a html string + */ + 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] + '"'; + }); + // Backport of 3.x void tag definition + 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 ? '' : ''); } - return url + (url.indexOf('?') === -1 ? '?' : '&') + hash; -}; -/** - * Turn a tag definition into a html string - */ -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] + '"'; - }); - // Backport of 3.x void tag definition - 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 ? '' : ''); -}; + /** + * Helper to return the absolute template path with a fallback loader + */ + getFullTemplatePath (template, context) { + // If the template doesn't use a loader use the lodash template loader + if (template.indexOf('!') === -1) { + template = require.resolve('./lib/loader.js') + '!' + path.resolve(context, template); + } + // Resolve template path + return template.replace( + /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/, + (match, prefix, filepath, postfix) => prefix + path.resolve(filepath) + postfix); + } -/** - * Helper to return the absolute template path with a fallback loader - */ -HtmlWebpackPlugin.prototype.getFullTemplatePath = function (template, context) { - // If the template doesn't use a loader use the lodash template loader - if (template.indexOf('!') === -1) { - template = require.resolve('./lib/loader.js') + '!' + path.resolve(context, template); + /** + * Helper to return a sorted unique array of all asset files out of the + * asset object + */ + 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; } - // Resolve template path - return template.replace( - /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/, - function (match, prefix, filepath, postfix) { - return prefix + path.resolve(filepath) + postfix; - }); -}; -/** - * Helper to return a sorted unique array of all asset files out of the - * asset object - */ -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; -}; + /** + * Helper to promisify compilation.applyPluginsAsyncWaterfall that returns + * a function that helps to merge given plugin arguments with processed ones + */ + 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) + ); + } -/** - * Helper to promisify compilation.applyPluginsAsyncWaterfall that returns - * a function that helps to merge given plugin arguments with processed ones - */ -HtmlWebpackPlugin.prototype.applyPluginsAsyncWaterfall = function (compilation) { - if (compilation.hooks) { - return function (eventName, requiresResult, pluginArgs) { - var ccEventName = trainCaseToCamelCase(eventName); - if (!compilation.hooks[ccEventName]) { - compilation.errors.push( - new Error('No hook found for ' + eventName) - ); - } + return compilation.hooks[ccEventName].promise(pluginArgs); + }; + } - return compilation.hooks[ccEventName].promise(pluginArgs); - }; - } else { // Before Webpack 4 - 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.') - ); + const promisedApplyPluginsAsyncWaterfall = function (name, init) { + return new Promise((resolve, reject) => { + const callback = function (err, result) { + if (err) { + return reject(err); } - return _.extend(pluginArgs, result); - }); + 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); + }); } -}; +} /** * Takes a string in train case and transforms it to camel case @@ -706,9 +661,7 @@ HtmlWebpackPlugin.prototype.applyPluginsAsyncWaterfall = function (compilation) * @param {string} word */ function trainCaseToCamelCase (word) { - return word.replace(/-([\w])/g, function (match, p1) { - return p1.toUpperCase(); - }); + return word.replace(/-([\w])/g, (match, p1) => p1.toUpperCase()); } module.exports = HtmlWebpackPlugin; diff --git a/lib/chunksorter.js b/lib/chunksorter.js index da2b9b36a..7555f3e4b 100644 --- a/lib/chunksorter.js +++ b/lib/chunksorter.js @@ -1,7 +1,7 @@ 'use strict'; -var toposort = require('toposort'); -var _ = require('lodash'); +const toposort = require('toposort'); +const _ = require('lodash'); /** Sorts dependencies between chunks by their "parents" attribute. @@ -32,14 +32,14 @@ module.exports.dependency = function (chunks, chunkGroups) { } // We build a map (chunk-id -> chunk) for faster access during graph building. - var nodeMap = {}; + const nodeMap = {}; chunks.forEach(function (chunk) { nodeMap[chunk.id] = chunk; }); // Next, we add an edge for each parent relationship into the graph - var edges = []; + let edges = []; if (chunkGroups) { // Add an edge for each parent (parent -> child) @@ -50,9 +50,9 @@ module.exports.dependency = function (chunks, chunkGroups) { }) ); }, []); - var sortedGroups = toposort.array(chunkGroups, edges); + const sortedGroups = toposort.array(chunkGroups, edges); // flatten chunkGroup into chunks - var sortedChunks = sortedGroups + const sortedChunks = sortedGroups .reduce(function (result, chunkGroup) { return result.concat(chunkGroup.chunks); }, []) @@ -62,9 +62,9 @@ module.exports.dependency = function (chunks, chunkGroups) { }) .filter(function (chunk, index, self) { // make sure exists (ie excluded chunks not in nodeMap) - var exists = !!chunk; + const exists = !!chunk; // make sure we have a unique list - var unique = self.indexOf(chunk) === index; + const unique = self.indexOf(chunk) === index; return exists && unique; }); return sortedChunks; @@ -75,7 +75,7 @@ module.exports.dependency = function (chunks, chunkGroups) { // Add an edge for each parent (parent -> child) chunk.parents.forEach(function (parentId) { // webpack2 chunk.parents are chunks instead of string id(s) - var parentChunk = _.isObject(parentId) ? parentId : nodeMap[parentId]; + const parentChunk = _.isObject(parentId) ? parentId : nodeMap[parentId]; // If the parent chunk does not exist (e.g. because of an excluded chunk) // we ignore that parent if (parentChunk) { @@ -120,8 +120,8 @@ module.exports.none = function (chunks) { * @return {Array} The sorted chunks */ module.exports.manual = function (chunks, specifyChunks) { - var chunksResult = []; - var filterResult = []; + const chunksResult = []; + let filterResult = []; if (Array.isArray(specifyChunks)) { for (var i = 0; i < specifyChunks.length; i++) { filterResult = chunks.filter(function (chunk) { diff --git a/lib/compiler.js b/lib/compiler.js index 747ef31f3..e3bdda649 100644 --- a/lib/compiler.js +++ b/lib/compiler.js @@ -5,14 +5,13 @@ * */ 'use strict'; -var Promise = require('bluebird'); -var _ = require('lodash'); -var path = require('path'); -var NodeTemplatePlugin = require('webpack/lib/node/NodeTemplatePlugin'); -var NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin'); -var LoaderTargetPlugin = require('webpack/lib/LoaderTargetPlugin'); -var LibraryTemplatePlugin = require('webpack/lib/LibraryTemplatePlugin'); -var SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin'); +const _ = require('lodash'); +const path = require('path'); +const NodeTemplatePlugin = require('webpack/lib/node/NodeTemplatePlugin'); +const NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin'); +const LoaderTargetPlugin = require('webpack/lib/LoaderTargetPlugin'); +const LibraryTemplatePlugin = require('webpack/lib/LibraryTemplatePlugin'); +const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin'); /** * Compiles the template into a nodejs factory, adds its to the compilation.assets @@ -33,17 +32,17 @@ var SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin'); module.exports.compileTemplate = function compileTemplate (template, context, outputFilename, compilation) { // The entry file is just an empty helper as the dynamic template // require is added in "loader.js" - var outputOptions = { + const outputOptions = { filename: outputFilename, publicPath: compilation.outputOptions.publicPath }; // Store the result of the parent compilation before we start the child compilation - var assetsBeforeCompilation = _.assign({}, compilation.assets[outputOptions.filename]); + const assetsBeforeCompilation = _.assign({}, compilation.assets[outputOptions.filename]); // Create an additional child compiler which takes the template // and turns it into an Node.JS html factory. // This allows us to use loaders during the compilation - var compilerName = getCompilerName(context, outputFilename); - var childCompiler = compilation.createChildCompiler(compilerName, outputOptions); + const compilerName = getCompilerName(context, outputFilename); + const childCompiler = compilation.createChildCompiler(compilerName, outputOptions); childCompiler.context = context; childCompiler.apply( new NodeTemplatePlugin(outputOptions), @@ -70,7 +69,7 @@ module.exports.compileTemplate = function compileTemplate (template, context, ou childCompiler.runAsChild(function (err, entries, childCompilation) { // Resolve / reject the promise if (childCompilation && childCompilation.errors && childCompilation.errors.length) { - var errorDetails = childCompilation.errors.map(function (error) { + const errorDetails = childCompilation.errors.map(function (error) { return error.message + (error.error ? ':\n' + error.error : ''); }).join('\n'); reject(new Error('Child compilation failed:\n' + errorDetails)); @@ -79,7 +78,7 @@ module.exports.compileTemplate = function compileTemplate (template, context, ou } else { // Replace [hash] placeholders in filename // In webpack 4 the plugin interface changed, so check for available fns - var outputName = compilation.mainTemplate.getAssetPath + const outputName = compilation.mainTemplate.getAssetPath ? compilation.mainTemplate.hooks.assetPath.call(outputOptions.filename, { hash: childCompilation.hash, chunk: entries[0] @@ -116,7 +115,7 @@ module.exports.compileTemplate = function compileTemplate (template, context, ou * Returns the child compiler name e.g. 'html-webpack-plugin for "index.html"' */ function getCompilerName (context, filename) { - var absolutePath = path.resolve(context, filename); - var relativePath = path.relative(context, absolutePath); + const absolutePath = path.resolve(context, filename); + const relativePath = path.relative(context, absolutePath); return 'html-webpack-plugin for "' + (absolutePath.length < relativePath.length ? absolutePath : relativePath) + '"'; } diff --git a/lib/errors.js b/lib/errors.js index ddf3562b1..2b946dad6 100644 --- a/lib/errors.js +++ b/lib/errors.js @@ -1,6 +1,6 @@ 'use strict'; -var PrettyError = require('pretty-error'); -var prettyError = new PrettyError(); +const PrettyError = require('pretty-error'); +const prettyError = new PrettyError(); prettyError.withoutColors(); prettyError.skipPackage(['html-plugin-evaluation']); prettyError.skipNodeFiles(); diff --git a/lib/loader.js b/lib/loader.js index 6b8bd0d8e..dd5d24832 100644 --- a/lib/loader.js +++ b/lib/loader.js @@ -1,14 +1,14 @@ /* This loader renders the template with underscore if no other loader was found */ 'use strict'; -var _ = require('lodash'); -var loaderUtils = require('loader-utils'); +const _ = require('lodash'); +const loaderUtils = require('loader-utils'); module.exports = function (source) { if (this.cacheable) { this.cacheable(); } - var allLoadersButThisOne = this.loaders.filter(function (loader) { + const allLoadersButThisOne = this.loaders.filter(function (loader) { // Loader API changed from `loader.module` to `loader.normal` in Webpack 2. return (loader.module || loader.normal) !== module.exports; }); @@ -24,15 +24,15 @@ module.exports = function (source) { // The following part renders the tempalte with lodash as aminimalistic loader // // Get templating options - var options = loaderUtils.parseQuery(this.query); + const options = loaderUtils.parseQuery(this.query); // Webpack 2 does not allow with() statements, which lodash templates use to unwrap // the parameters passed to the compiled template inside the scope. We therefore // need to unwrap them ourselves here. This is essentially what lodash does internally // To tell lodash it should not use with we set a variable - var template = _.template(source, _.defaults(options, { variable: 'data' })); + const template = _.template(source, _.defaults(options, { variable: 'data' })); // All templateVariables which should be available // @see HtmlWebpackPlugin.prototype.executeTemplate - var templateVariables = [ + const templateVariables = [ 'compilation', 'webpack', 'webpackConfig', diff --git a/package.json b/package.json index 720a345d7..042bf1ac4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "html-webpack-plugin", - "version": "2.30.1", + "version": "3.0.0", "license": "MIT", "description": "Simplifies creation of HTML files to serve your webpack bundles", "author": "Charles Blaxland (https://github.com/ampedandwired)", @@ -43,13 +43,13 @@ "webpack-recompilation-simulator": "^1.3.0" }, "dependencies": { - "bluebird": "^3.4.7", "html-minifier": "^3.2.3", "loader-utils": "^0.2.16", "lodash": "^4.17.3", "pretty-error": "^2.0.2", "tapable": "^1.0.0", - "toposort": "^1.0.0" + "toposort": "^1.0.0", + "util.promisify": "1.0.0" }, "peerDependencies": { "extract-text-webpack-plugin": "^1.0.0 || ^2.0.0 || 3.0.0 || ^4.0.0-alpha.0 || ^4.0.0", @@ -63,5 +63,8 @@ ], "bugs": "https://github.com/jantimon/html-webpack-plugin/issues", "homepage": "https://github.com/jantimon/html-webpack-plugin", - "repository": "https://github.com/jantimon/html-webpack-plugin.git" + "repository": "https://github.com/jantimon/html-webpack-plugin.git", + "engines": { + "node": ">=6.11.5" + } }