From 0b0e0205fc893d90bca4d71cfdff26cb2877ba26 Mon Sep 17 00:00:00 2001 From: Jan Nicklas Date: Mon, 23 Nov 2015 12:00:38 +0100 Subject: [PATCH] Allow to disable sorting or pass a custom sort function --- README.md | 1 + index.js | 35 ++++++++++++++++++++++++++++------- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 7e4323f..36fa266 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ Allowed values are as follows: included scripts and css files. This is useful for cache busting. - `chunks`: Allows you to add only some chunks (e.g. only the unit-test chunk) - `excludeChunks`: Allows you to skip some chunks (e.g. don't add the unit-test chunk) +- `chunksSortMode`: Allows to controll how chunks should be sorted before they are included to the html. Allowed values: 'none' | 'default' | {function} - default: 'auto' Here's an example webpack config illustrating how to use these options: ```javascript diff --git a/index.js b/index.js index 5030639..b2135ab 100644 --- a/index.js +++ b/index.js @@ -170,6 +170,32 @@ HtmlWebpackPlugin.prototype.addFileToAssets = function(compilation, filename) { }); }; +/** + * Helper to sort chunks + */ +HtmlWebpackPlugin.prototype.sortChunks = function(chunks, sortMode) { + // Sort mode auto by default: + if (typeof sortMode === 'undefined' || sortMode === 'auto') { + return chunks.sort(function orderEntryLast(a, b) { + if (a.entry !== b.entry) { + return b.entry ? 1 : -1; + } else { + return b.id - a.id; + } + }); + } + // Disabled sorting: + if (sortMode === 'none') { + return chunks; + } + // Custom function + if (typeof sortMode === 'function') { + return chunks.sort(sortMode); + } + // Invalid sort mode + throw new Error('"' + sortMode + '" is not a valid chunk sort mode'); +}; + HtmlWebpackPlugin.prototype.htmlWebpackPluginAssets = function(compilation, webpackStatsJson, includedChunks, excludedChunks) { var self = this; @@ -203,13 +229,8 @@ HtmlWebpackPlugin.prototype.htmlWebpackPluginAssets = function(compilation, webp assets.favicon = self.appendHash(assets.favicon, webpackStatsJson.hash); } - var chunks = webpackStatsJson.chunks.sort(function orderEntryLast(a, b) { - if (a.entry !== b.entry) { - return b.entry ? 1 : -1; - } else { - return b.id - a.id; - } - }); + // Get sorted chunks + var chunks = HtmlWebpackPlugin.prototype.sortChunks(webpackStatsJson.chunks, this.options.chunksSortMode); for (var i = 0; i < chunks.length; i++) { var chunk = chunks[i];