analyzer.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. "use strict";
  2. const fs = require('fs');
  3. const path = require('path');
  4. const _ = require('lodash');
  5. const gzipSize = require('gzip-size');
  6. const Logger = require('./Logger');
  7. const Folder = require('./tree/Folder').default;
  8. const {
  9. parseBundle
  10. } = require('./parseUtils');
  11. const {
  12. createAssetsFilter
  13. } = require('./utils');
  14. const FILENAME_QUERY_REGEXP = /\?.*$/u;
  15. const FILENAME_EXTENSIONS = /\.(js|mjs)$/iu;
  16. module.exports = {
  17. getViewerData,
  18. readStatsFromFile
  19. };
  20. function getViewerData(bundleStats, bundleDir, opts) {
  21. const {
  22. logger = new Logger(),
  23. excludeAssets = null
  24. } = opts || {};
  25. const isAssetIncluded = createAssetsFilter(excludeAssets); // Sometimes all the information is located in `children` array (e.g. problem in #10)
  26. if (_.isEmpty(bundleStats.assets) && !_.isEmpty(bundleStats.children)) {
  27. const {
  28. children
  29. } = bundleStats;
  30. bundleStats = bundleStats.children[0]; // Sometimes if there are additional child chunks produced add them as child assets,
  31. // leave the 1st one as that is considered the 'root' asset.
  32. for (let i = 1; i < children.length; i++) {
  33. bundleStats.children[i].assets.forEach(asset => {
  34. asset.isChild = true;
  35. bundleStats.assets.push(asset);
  36. });
  37. }
  38. } else if (!_.isEmpty(bundleStats.children)) {
  39. // Sometimes if there are additional child chunks produced add them as child assets
  40. bundleStats.children.forEach(child => {
  41. child.assets.forEach(asset => {
  42. asset.isChild = true;
  43. bundleStats.assets.push(asset);
  44. });
  45. });
  46. } // Picking only `*.js or *.mjs` assets from bundle that has non-empty `chunks` array
  47. bundleStats.assets = _.filter(bundleStats.assets, asset => {
  48. // Removing query part from filename (yes, somebody uses it for some reason and Webpack supports it)
  49. // See #22
  50. asset.name = asset.name.replace(FILENAME_QUERY_REGEXP, '');
  51. return FILENAME_EXTENSIONS.test(asset.name) && !_.isEmpty(asset.chunks) && isAssetIncluded(asset.name);
  52. }); // Trying to parse bundle assets and get real module sizes if `bundleDir` is provided
  53. let bundlesSources = null;
  54. let parsedModules = null;
  55. if (bundleDir) {
  56. bundlesSources = {};
  57. parsedModules = {};
  58. for (const statAsset of bundleStats.assets) {
  59. const assetFile = path.join(bundleDir, statAsset.name);
  60. let bundleInfo;
  61. try {
  62. bundleInfo = parseBundle(assetFile);
  63. } catch (err) {
  64. const msg = err.code === 'ENOENT' ? 'no such file' : err.message;
  65. logger.warn(`Error parsing bundle asset "${assetFile}": ${msg}`);
  66. continue;
  67. }
  68. bundlesSources[statAsset.name] = bundleInfo.src;
  69. _.assign(parsedModules, bundleInfo.modules);
  70. }
  71. if (_.isEmpty(bundlesSources)) {
  72. bundlesSources = null;
  73. parsedModules = null;
  74. logger.warn('\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n');
  75. }
  76. }
  77. const assets = _.transform(bundleStats.assets, (result, statAsset) => {
  78. // If asset is a childAsset, then calculate appropriate bundle modules by looking through stats.children
  79. const assetBundles = statAsset.isChild ? getChildAssetBundles(bundleStats, statAsset.name) : bundleStats;
  80. const modules = assetBundles ? getBundleModules(assetBundles) : [];
  81. const asset = result[statAsset.name] = _.pick(statAsset, 'size');
  82. if (bundlesSources && _.has(bundlesSources, statAsset.name)) {
  83. asset.parsedSize = Buffer.byteLength(bundlesSources[statAsset.name]);
  84. asset.gzipSize = gzipSize.sync(bundlesSources[statAsset.name]);
  85. } // Picking modules from current bundle script
  86. asset.modules = _(modules).filter(statModule => assetHasModule(statAsset, statModule)).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(fs.readFileSync(filename, 'utf8'));
  110. }
  111. function getChildAssetBundles(bundleStats, assetName) {
  112. return _.find(bundleStats.children, c => _(c.assetsByChunkName).values().flatten().includes(assetName));
  113. }
  114. function getBundleModules(bundleStats) {
  115. return _(bundleStats.chunks).map('modules').concat(bundleStats.modules).compact().flatten().uniqBy('id').value();
  116. }
  117. function assetHasModule(statAsset, statModule) {
  118. // Checking if this module is the part of asset chunks
  119. return _.some(statModule.chunks, moduleChunk => _.includes(statAsset.chunks, moduleChunk));
  120. }
  121. function createModulesTree(modules) {
  122. const root = new Folder('.');
  123. _.each(modules, module => root.addModule(module));
  124. root.mergeNestedFolders();
  125. return root;
  126. }