Last active
November 8, 2016 17:50
-
-
Save mzgoddard/3c39a9f46c9e918985d5b109a95f050b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function DepthFirstPostPlugin() {} | |
module.exports = DepthFirstPostPlugin; | |
DepthFirstPostPlugin.prototype.apply = function(compiler) { | |
compiler.plugin('compilation', function(compilation) { | |
compilation.plugin('optimize-chunk-order', function(chunks) { | |
var checked = {}; | |
function walk(chunk) { | |
var nextIndex = 0; | |
chunk.modules.sort(function(a, b) { | |
return compilation.modules.indexOf(a) - compilation.modules.indexOf(a); | |
}); | |
var hasher = require('crypto').createHash('md5'); | |
chunk.updateHash(hasher); | |
var ident = hasher.digest('hex'); | |
if (checked[ident]) {return;} | |
checked[ident] = true; | |
chunk.modules.forEach(function(module) { | |
module.blocks.forEach(function(block) { | |
var index = chunk.chunks.reduce(function(carry, chunk, index) { | |
if (carry !== -1) {return carry;} | |
return chunk.origins.reduce(function(carry, origin) { | |
if (carry !== -1) {return carry;} | |
return origin.module === module ? index : -1; | |
}, -1); | |
}, -1); | |
if (index !== -1) { | |
var child = chunk.chunks[index]; | |
chunk.chunks.splice(index, 1); | |
chunk.chunks.splice(nextIndex, 0, child); | |
nextIndex++; | |
} | |
}); | |
}); | |
} | |
chunks.forEach(walk); | |
checked = {}; | |
var nextIndex = 0; | |
compilation.entries.forEach(function(module) { | |
module.chunks[0].forEach(function(chunk) { | |
var hasher = require('crypto').createHash('md5'); | |
chunk.updateHash(hasher); | |
var ident = hasher.digest('hex'); | |
if (checked[ident]) {return;} | |
checked[ident] = true; | |
var index = chunks.indexOf(chunk); | |
if (index !== -1) { | |
chunks.splice(index, 1); | |
chunks.splice(nextIndex, 0, chunk); | |
nextIndex++; | |
} | |
}); | |
}); | |
}); | |
compilation.plugin('optimize-module-order', function(modules) { | |
var nextIndex = 0; | |
var checked = {}; | |
function walkDep(dep) { | |
if (dep.module) { | |
walk(dep.module); | |
} | |
} | |
function walkDepsOwner(owner) { | |
owner.dependencies.forEach(walkDep); | |
} | |
function walk(module) { | |
var ident = module.identifier(); | |
if (checked[ident]) {return;} | |
checked[ident] = true; | |
walkDepsOwner(module); | |
module.variables.forEach(walkDepsOwner); | |
module.blocks.forEach(walkDepsOwner); | |
var index = modules.indexOf(module); | |
if (index !== -1) { | |
modules.splice(index, 1); | |
modules.splice(nextIndex, 0, module); | |
nextIndex++; | |
} | |
} | |
compilation.entries.forEach(walk); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment