analyzer.js 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. const fs = require('fs');
  2. const path = require('path');
  3. const _ = require('lodash');
  4. const gzipSize = require('gzip-size');
  5. const Logger = require('./Logger');
  6. const Folder = require('./tree/Folder').default;
  7. const { parseBundle } = require('./parseUtils');
  8. const { createAssetsFilter } = require('./utils');
  9. const FILENAME_QUERY_REGEXP = /\?.*$/;
  10. module.exports = {
  11. getViewerData,
  12. readStatsFromFile
  13. };
  14. function getViewerData(bundleStats, bundleDir, opts) {
  15. const {
  16. logger = new Logger(),
  17. excludeAssets = null
  18. } = opts || {};
  19. const isAssetIncluded = createAssetsFilter(excludeAssets);
  20. // Sometimes all the information is located in `children` array (e.g. problem in #10)
  21. if (_.isEmpty(bundleStats.assets) && !_.isEmpty(bundleStats.children)) {
  22. bundleStats = bundleStats.children[0];
  23. }
  24. // Picking only `*.js` assets from bundle that has non-empty `chunks` array
  25. bundleStats.assets = _.filter(bundleStats.assets, asset => {
  26. // Removing query part from filename (yes, somebody uses it for some reason and Webpack supports it)
  27. // See #22
  28. asset.name = asset.name.replace(FILENAME_QUERY_REGEXP, '');
  29. return _.endsWith(asset.name, '.js') && !_.isEmpty(asset.chunks) && isAssetIncluded(asset.name);
  30. });
  31. // Trying to parse bundle assets and get real module sizes if `bundleDir` is provided
  32. let bundlesSources = null;
  33. let parsedModules = null;
  34. if (bundleDir) {
  35. bundlesSources = {};
  36. parsedModules = {};
  37. for (const statAsset of bundleStats.assets) {
  38. const assetFile = path.join(bundleDir, statAsset.name);
  39. let bundleInfo;
  40. try {
  41. bundleInfo = parseBundle(assetFile);
  42. } catch (err) {
  43. const msg = (err.code === 'ENOENT') ? 'no such file' : err.message;
  44. logger.warn(`Error parsing bundle asset "${assetFile}": ${msg}`);
  45. continue;
  46. }
  47. bundlesSources[statAsset.name] = bundleInfo.src;
  48. _.assign(parsedModules, bundleInfo.modules);
  49. }
  50. if (_.isEmpty(bundlesSources)) {
  51. bundlesSources = null;
  52. parsedModules = null;
  53. logger.warn('\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n');
  54. }
  55. }
  56. const modules = getBundleModules(bundleStats);
  57. const assets = _.transform(bundleStats.assets, (result, statAsset) => {
  58. const asset = result[statAsset.name] = _.pick(statAsset, 'size');
  59. if (bundlesSources && _.has(bundlesSources, statAsset.name)) {
  60. asset.parsedSize = bundlesSources[statAsset.name].length;
  61. asset.gzipSize = gzipSize.sync(bundlesSources[statAsset.name]);
  62. }
  63. // Picking modules from current bundle script
  64. asset.modules = _(modules)
  65. .filter(statModule => assetHasModule(statAsset, statModule))
  66. .each(statModule => {
  67. if (parsedModules) {
  68. statModule.parsedSrc = parsedModules[statModule.id];
  69. }
  70. });
  71. asset.tree = createModulesTree(asset.modules);
  72. }, {});
  73. return _.transform(assets, (result, asset, filename) => {
  74. result.push({
  75. label: filename,
  76. // Not using `asset.size` here provided by Webpack because it can be very confusing when `UglifyJsPlugin` is used.
  77. // In this case all module sizes from stats file will represent unminified module sizes, but `asset.size` will
  78. // be the size of minified bundle.
  79. // Using `asset.size` only if current asset doesn't contain any modules (resulting size equals 0)
  80. statSize: asset.tree.size || asset.size,
  81. parsedSize: asset.parsedSize,
  82. gzipSize: asset.gzipSize,
  83. groups: _.invokeMap(asset.tree.children, 'toChartData')
  84. });
  85. }, []);
  86. }
  87. function readStatsFromFile(filename) {
  88. return JSON.parse(
  89. fs.readFileSync(filename, 'utf8')
  90. );
  91. }
  92. function getBundleModules(bundleStats) {
  93. return _(bundleStats.chunks)
  94. .map('modules')
  95. .concat(bundleStats.modules)
  96. .compact()
  97. .flatten()
  98. .uniqBy('id')
  99. .value();
  100. }
  101. function assetHasModule(statAsset, statModule) {
  102. // Checking if this module is the part of asset chunks
  103. return _.some(statModule.chunks, moduleChunk =>
  104. _.includes(statAsset.chunks, moduleChunk)
  105. );
  106. }
  107. function createModulesTree(modules) {
  108. const root = new Folder('.');
  109. _.each(modules, module => root.addModule(module));
  110. return root;
  111. }