analyzer.js 5.1 KB

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