64c98cf9d7e0ead9d316f672a3d141e52aa68f5ffed06ca975cae6ad5bc3018f2c1be3f1546380dd25459f0b3dee4c7b8e1d5348975e6b87e35482b15a6a8d 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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 = /\?.*$/u;
  10. const FILENAME_EXTENSIONS = /\.(js|mjs)$/iu;
  11. module.exports = {
  12. getViewerData,
  13. readStatsFromFile
  14. };
  15. function getViewerData(bundleStats, bundleDir, opts) {
  16. const {
  17. logger = new Logger(),
  18. excludeAssets = null
  19. } = opts || {};
  20. const isAssetIncluded = createAssetsFilter(excludeAssets);
  21. // Sometimes all the information is located in `children` array (e.g. problem in #10)
  22. if (_.isEmpty(bundleStats.assets) && !_.isEmpty(bundleStats.children)) {
  23. const {children} = bundleStats;
  24. bundleStats = bundleStats.children[0];
  25. // Sometimes if there are additional child chunks produced add them as child assets,
  26. // leave the 1st one as that is considered the 'root' asset.
  27. for (let i = 1; i < children.length; i++) {
  28. bundleStats.children[i].assets.forEach((asset) => {
  29. asset.isChild = true;
  30. bundleStats.assets.push(asset);
  31. });
  32. }
  33. } else if (!_.isEmpty(bundleStats.children)) {
  34. // Sometimes if there are additional child chunks produced add them as child assets
  35. bundleStats.children.forEach((child) => {
  36. child.assets.forEach((asset) => {
  37. asset.isChild = true;
  38. bundleStats.assets.push(asset);
  39. });
  40. });
  41. }
  42. // Picking only `*.js or *.mjs` assets from bundle that has non-empty `chunks` array
  43. bundleStats.assets = _.filter(bundleStats.assets, asset => {
  44. // Removing query part from filename (yes, somebody uses it for some reason and Webpack supports it)
  45. // See #22
  46. asset.name = asset.name.replace(FILENAME_QUERY_REGEXP, '');
  47. return FILENAME_EXTENSIONS.test(asset.name) && !_.isEmpty(asset.chunks) && isAssetIncluded(asset.name);
  48. });
  49. // Trying to parse bundle assets and get real module sizes if `bundleDir` is provided
  50. let bundlesSources = null;
  51. let parsedModules = null;
  52. if (bundleDir) {
  53. bundlesSources = {};
  54. parsedModules = {};
  55. for (const statAsset of bundleStats.assets) {
  56. const assetFile = path.join(bundleDir, statAsset.name);
  57. let bundleInfo;
  58. try {
  59. bundleInfo = parseBundle(assetFile);
  60. } catch (err) {
  61. const msg = (err.code === 'ENOENT') ? 'no such file' : err.message;
  62. logger.warn(`Error parsing bundle asset "${assetFile}": ${msg}`);
  63. continue;
  64. }
  65. bundlesSources[statAsset.name] = bundleInfo.src;
  66. _.assign(parsedModules, bundleInfo.modules);
  67. }
  68. if (_.isEmpty(bundlesSources)) {
  69. bundlesSources = null;
  70. parsedModules = null;
  71. logger.warn('\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n');
  72. }
  73. }
  74. const assets = _.transform(bundleStats.assets, (result, statAsset) => {
  75. // If asset is a childAsset, then calculate appropriate bundle modules by looking through stats.children
  76. const assetBundles = statAsset.isChild ? getChildAssetBundles(bundleStats, statAsset.name) : bundleStats;
  77. const modules = assetBundles ? getBundleModules(assetBundles) : [];
  78. const asset = result[statAsset.name] = _.pick(statAsset, 'size');
  79. if (bundlesSources && _.has(bundlesSources, statAsset.name)) {
  80. asset.parsedSize = Buffer.byteLength(bundlesSources[statAsset.name]);
  81. asset.gzipSize = gzipSize.sync(bundlesSources[statAsset.name]);
  82. }
  83. // Picking modules from current bundle script
  84. asset.modules = _(modules)
  85. .filter(statModule => assetHasModule(statAsset, statModule))
  86. .each(statModule => {
  87. if (parsedModules) {
  88. statModule.parsedSrc = parsedModules[statModule.id];
  89. }
  90. });
  91. asset.tree = createModulesTree(asset.modules);
  92. }, {});
  93. return _.transform(assets, (result, asset, filename) => {
  94. result.push({
  95. label: filename,
  96. isAsset: true,
  97. // Not using `asset.size` here provided by Webpack because it can be very confusing when `UglifyJsPlugin` is used.
  98. // In this case all module sizes from stats file will represent unminified module sizes, but `asset.size` will
  99. // be the size of minified bundle.
  100. // Using `asset.size` only if current asset doesn't contain any modules (resulting size equals 0)
  101. statSize: asset.tree.size || asset.size,
  102. parsedSize: asset.parsedSize,
  103. gzipSize: asset.gzipSize,
  104. groups: _.invokeMap(asset.tree.children, 'toChartData')
  105. });
  106. }, []);
  107. }
  108. function readStatsFromFile(filename) {
  109. return JSON.parse(
  110. fs.readFileSync(filename, 'utf8')
  111. );
  112. }
  113. function getChildAssetBundles(bundleStats, assetName) {
  114. return _.find(bundleStats.children, (c) =>
  115. _(c.assetsByChunkName)
  116. .values()
  117. .flatten()
  118. .includes(assetName)
  119. );
  120. }
  121. function getBundleModules(bundleStats) {
  122. return _(bundleStats.chunks)
  123. .map('modules')
  124. .concat(bundleStats.modules)
  125. .compact()
  126. .flatten()
  127. .uniqBy('id')
  128. .value();
  129. }
  130. function assetHasModule(statAsset, statModule) {
  131. // Checking if this module is the part of asset chunks
  132. return _.some(statModule.chunks, moduleChunk =>
  133. _.includes(statAsset.chunks, moduleChunk)
  134. );
  135. }
  136. function createModulesTree(modules) {
  137. const root = new Folder('.');
  138. _.each(modules, module => root.addModule(module));
  139. root.mergeNestedFolders();
  140. return root;
  141. }