Allow to disable sorting or pass a custom sort function

This commit is contained in:
Jan Nicklas 2015-11-23 12:04:42 +01:00 committed by Jan Nicklas
parent 5305da7b15
commit ec36061b03
2 changed files with 30 additions and 8 deletions

View File

@ -69,6 +69,7 @@ Allowed values are as follows:
- `hash`: `true | false` if `true` then append a unique webpack compilation hash to all
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)
- `chunksSortMode`: Allows to controll how chunks should be sorted before they are included to the html. Allowed values: 'none' | 'default' | {function} - default: 'auto'
- `excludeChunks`: Allows you to skip some chunks (e.g. don't add the unit-test chunk)
Here's an example webpack config illustrating how to use these options:

View File

@ -56,6 +56,8 @@ HtmlWebpackPlugin.prototype.apply = function(compiler) {
compiler.plugin('emit', function(compilation, callback) {
// Get all chunks
var chunks = self.filterChunks(compilation.getStats().toJson(), self.options.chunks, self.options.excludeChunks);
// Sort chunks
chunks = self.sortChunks(chunks, self.options.chunksSortMode);
// Get assets
var assets = self.htmlWebpackPluginAssets(compilation, chunks);
Promise.resolve()
@ -290,11 +292,37 @@ HtmlWebpackPlugin.prototype.addFileToAssets = function(filename, compilation) {
});
};
/**
* 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');
};
/**
* Return all chunks from the compilation result which match the exclude and include filters
*/
HtmlWebpackPlugin.prototype.filterChunks = function (webpackStatsJson, includedChunks, excludedChunks) {
var chunks = webpackStatsJson.chunks.filter(function(chunk){
return webpackStatsJson.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) {
@ -315,13 +343,6 @@ HtmlWebpackPlugin.prototype.filterChunks = function (webpackStatsJson, includedC
// Add otherwise
return true;
});
return chunks.sort(function orderEntryLast(a, b) {
if (a.entry !== b.entry) {
return b.entry ? 1 : -1;
} else {
return b.id - a.id;
}
});
};
HtmlWebpackPlugin.prototype.htmlWebpackPluginAssets = function(compilation, chunks) {