Skip to content

Instantly share code, notes, and snippets.

@kisenka
Last active November 30, 2021 22:37
Show Gist options
  • Save kisenka/b31d3dd1d1a9182dde0bb3e3efe1a038 to your computer and use it in GitHub Desktop.
Save kisenka/b31d3dd1d1a9182dde0bb3e3efe1a038 to your computer and use it in GitHub Desktop.
Extract assets from Webpack compilation
/**
* @param {Compilation} compilation Webpack compilation
* @returns {{
* byChunkName: {chunkName: Array<{name: string, source: string}>},
* extra: Array<{name: string, source: string}>
* }}
*/
var getAssets = function (compilation) {
var EXTRA_ASSETS_CHUNK_NAME = '__extra_assets__';
var stats = compilation.getStats().toJson();
var compiledAssets = compilation.assets;
var chunks = {};
stats.assets.forEach(function (assetInfo) {
assetInfo.chunkNames.forEach(function (chunkName) {
if (chunkName in chunks == false)
chunks[chunkName] = [];
chunks[chunkName].push({
name: assetInfo.name
})
});
});
// Assets with no chunks
var extraAssets = stats.assets.filter(function(assetInfo) {
return assetInfo.chunks.length == 0
}).map(function(assetInfo) {
return {
name: assetInfo.name
}
});
chunks[EXTRA_ASSETS_CHUNK_NAME] = extraAssets;
// Sources
for (var chunkName in chunks) {
var assets = chunks[chunkName];
assets.forEach(function(asset) {
if (asset.name in compiledAssets)
asset.source = compiledAssets[asset.name].source();
})
}
delete chunks[EXTRA_ASSETS_CHUNK_NAME];
return {
byChunkName: chunks,
extra: extraAssets
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment