analyzeBundle.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // From https://github.com/webpack-contrib/webpack-bundle-analyzer/blob/ba3dbd71cec7becec0fbf529833204425f66efde/src/parseUtils.js
  2. // Modified by Guillaume Chau (Akryum)
  3. const acorn = require('acorn')
  4. const walk = require('acorn-walk')
  5. const mapValues = require('lodash.mapvalues')
  6. const transform = require('lodash.transform')
  7. const zlib = require('zlib')
  8. const { warn } = require('@vue/cli-shared-utils')
  9. exports.analyzeBundle = function analyzeBundle (bundleStats, assetSources) {
  10. // Picking only `*.js` assets from bundle that has non-empty `chunks` array
  11. const jsAssets = []
  12. const otherAssets = []
  13. // Separate JS assets
  14. bundleStats.assets.forEach(asset => {
  15. if (asset.name.endsWith('.js') && asset.chunks && asset.chunks.length) {
  16. jsAssets.push(asset)
  17. } else {
  18. otherAssets.push(asset)
  19. }
  20. })
  21. // Trying to parse bundle assets and get real module sizes
  22. let bundlesSources = null
  23. let parsedModules = null
  24. bundlesSources = {}
  25. parsedModules = {}
  26. for (const asset of jsAssets) {
  27. const source = assetSources.get(asset.name)
  28. let bundleInfo
  29. try {
  30. bundleInfo = parseBundle(source)
  31. } catch (err) {
  32. bundleInfo = null
  33. }
  34. if (!bundleInfo) {
  35. warn(
  36. `\nCouldn't parse bundle asset "${asset.fullPath}".\n` +
  37. 'Analyzer will use module sizes from stats file.\n'
  38. )
  39. parsedModules = null
  40. bundlesSources = null
  41. break
  42. }
  43. bundlesSources[asset.name] = bundleInfo.src
  44. Object.assign(parsedModules, bundleInfo.modules)
  45. }
  46. // Update sizes
  47. bundleStats.modules.forEach(module => {
  48. const parsedSrc = parsedModules && parsedModules[module.id]
  49. module.size = {
  50. stats: module.size
  51. }
  52. if (parsedSrc) {
  53. module.size.parsed = parsedSrc.length
  54. module.size.gzip = getGzipSize(parsedSrc)
  55. } else {
  56. module.size.parsed = module.size.stats
  57. module.size.gzip = 0
  58. }
  59. })
  60. jsAssets.forEach(asset => {
  61. const src = bundlesSources && bundlesSources[asset.name]
  62. asset.size = {
  63. stats: asset.size
  64. }
  65. if (src) {
  66. asset.size.parsed = src.length
  67. asset.size.gzip = getGzipSize(src)
  68. } else {
  69. asset.size.parsed = asset.size.stats
  70. asset.size.gzip = 0
  71. }
  72. }, {})
  73. otherAssets.forEach(asset => {
  74. const src = assetSources.get(asset.name)
  75. asset.size = {
  76. stats: asset.size,
  77. parsed: asset.size
  78. }
  79. if (src) {
  80. asset.size.gzip = getGzipSize(src)
  81. } else {
  82. asset.size.gzip = 0
  83. }
  84. })
  85. }
  86. function parseBundle (bundleContent) {
  87. const ast = acorn.parse(bundleContent, {
  88. sourceType: 'script',
  89. // I believe in a bright future of ECMAScript!
  90. // Actually, it's set to `2050` to support the latest ECMAScript version that currently exists.
  91. // Seems like `acorn` supports such weird option value.
  92. ecmaVersion: 2050
  93. })
  94. const walkState = {
  95. locations: null
  96. }
  97. walk.recursive(
  98. ast,
  99. walkState,
  100. {
  101. CallExpression (node, state, c) {
  102. if (state.sizes) return
  103. const args = node.arguments
  104. // Additional bundle without webpack loader.
  105. // Modules are stored in second argument, after chunk ids:
  106. // webpackJsonp([<chunks>], <modules>, ...)
  107. // As function name may be changed with `output.jsonpFunction` option we can't rely on it's default name.
  108. if (
  109. node.callee.type === 'Identifier' &&
  110. args.length >= 2 &&
  111. isArgumentContainsChunkIds(args[0]) &&
  112. isArgumentContainsModulesList(args[1])
  113. ) {
  114. state.locations = getModulesLocationFromFunctionArgument(args[1])
  115. return
  116. }
  117. // Additional bundle without webpack loader, with module IDs optimized.
  118. // Modules are stored in second arguments Array(n).concat() call
  119. // webpackJsonp([<chunks>], Array([minimum ID]).concat([<module>, <module>, ...]))
  120. // As function name may be changed with `output.jsonpFunction` option we can't rely on it's default name.
  121. if (
  122. node.callee.type === 'Identifier' &&
  123. (args.length === 2 || args.length === 3) &&
  124. isArgumentContainsChunkIds(args[0]) &&
  125. isArgumentArrayConcatContainingChunks(args[1])
  126. ) {
  127. state.locations = getModulesLocationFromArrayConcat(args[1])
  128. return
  129. }
  130. // Main bundle with webpack loader
  131. // Modules are stored in first argument:
  132. // (function (...) {...})(<modules>)
  133. if (
  134. node.callee.type === 'FunctionExpression' &&
  135. !node.callee.id &&
  136. args.length === 1 &&
  137. isArgumentContainsModulesList(args[0])
  138. ) {
  139. state.locations = getModulesLocationFromFunctionArgument(args[0])
  140. return
  141. }
  142. // Additional bundles with webpack 4 are loaded with:
  143. // (window.webpackJsonp=window.webpackJsonp||[]).push([[chunkId], [<module>, <module>], [[optional_entries]]]);
  144. if (
  145. isWindowPropertyPushExpression(node) &&
  146. args.length === 1 &&
  147. isArgumentContainingChunkIdsAndModulesList(args[0])
  148. ) {
  149. state.locations = getModulesLocationFromFunctionArgument(args[0].elements[1])
  150. return
  151. }
  152. // Walking into arguments because some of plugins (e.g. `DedupePlugin`) or some Webpack
  153. // features (e.g. `umd` library output) can wrap modules list into additional IIFE.
  154. args.forEach(arg => c(arg, state))
  155. }
  156. }
  157. )
  158. if (!walkState.locations) {
  159. return null
  160. }
  161. return {
  162. src: bundleContent,
  163. modules: mapValues(walkState.locations,
  164. loc => bundleContent.slice(loc.start, loc.end)
  165. )
  166. }
  167. }
  168. function getGzipSize (buffer) {
  169. return zlib.gzipSync(buffer).length
  170. }
  171. function isArgumentContainsChunkIds (arg) {
  172. // Array of numeric or string ids. Chunk IDs are strings when NamedChunksPlugin is used
  173. return (arg.type === 'ArrayExpression' && arg.elements.every(isModuleId))
  174. }
  175. function isArgumentContainsModulesList (arg) {
  176. if (arg.type === 'ObjectExpression') {
  177. return arg.properties
  178. .map(prop => prop.value)
  179. .every(isModuleWrapper)
  180. }
  181. if (arg.type === 'ArrayExpression') {
  182. // Modules are contained in array.
  183. // Array indexes are module ids
  184. return arg.elements.every(elem =>
  185. // Some of array items may be skipped because there is no module with such id
  186. !elem ||
  187. isModuleWrapper(elem)
  188. )
  189. }
  190. return false
  191. }
  192. function isArgumentContainingChunkIdsAndModulesList (arg) {
  193. if (
  194. arg.type === 'ArrayExpression' &&
  195. arg.elements.length >= 2 &&
  196. isArgumentContainsChunkIds(arg.elements[0]) &&
  197. isArgumentContainsModulesList(arg.elements[1])
  198. ) {
  199. return true
  200. }
  201. return false
  202. }
  203. function isArgumentArrayConcatContainingChunks (arg) {
  204. if (
  205. arg.type === 'CallExpression' &&
  206. arg.callee.type === 'MemberExpression' &&
  207. // Make sure the object called is `Array(<some number>)`
  208. arg.callee.object.type === 'CallExpression' &&
  209. arg.callee.object.callee.type === 'Identifier' &&
  210. arg.callee.object.callee.name === 'Array' &&
  211. arg.callee.object.arguments.length === 1 &&
  212. isNumericId(arg.callee.object.arguments[0]) &&
  213. // Make sure the property X called for `Array(<some number>).X` is `concat`
  214. arg.callee.property.type === 'Identifier' &&
  215. arg.callee.property.name === 'concat' &&
  216. // Make sure exactly one array is passed in to `concat`
  217. arg.arguments.length === 1 &&
  218. arg.arguments[0].type === 'ArrayExpression'
  219. ) {
  220. // Modules are contained in `Array(<minimum ID>).concat(` array:
  221. // https://github.com/webpack/webpack/blob/v1.14.0/lib/Template.js#L91
  222. // The `<minimum ID>` + array indexes are module ids
  223. return true
  224. }
  225. return false
  226. }
  227. function isWindowPropertyPushExpression (node) {
  228. return node.callee.type === 'MemberExpression' &&
  229. node.callee.property.name === 'push' &&
  230. node.callee.object.type === 'AssignmentExpression' &&
  231. node.callee.object.left.object.name === 'window'
  232. }
  233. function isModuleWrapper (node) {
  234. return (
  235. // It's an anonymous function expression that wraps module
  236. ((node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') && !node.id) ||
  237. // If `DedupePlugin` is used it can be an ID of duplicated module...
  238. isModuleId(node) ||
  239. // or an array of shape [<module_id>, ...args]
  240. (node.type === 'ArrayExpression' && node.elements.length > 1 && isModuleId(node.elements[0]))
  241. )
  242. }
  243. function isModuleId (node) {
  244. return (node.type === 'Literal' && (isNumericId(node) || typeof node.value === 'string'))
  245. }
  246. function isNumericId (node) {
  247. return (node.type === 'Literal' && Number.isInteger(node.value) && node.value >= 0)
  248. }
  249. function getModulesLocationFromFunctionArgument (arg) {
  250. if (arg.type === 'ObjectExpression') {
  251. const modulesNodes = arg.properties
  252. return transform(modulesNodes, (result, moduleNode) => {
  253. const moduleId = moduleNode.key.name || moduleNode.key.value
  254. result[moduleId] = getModuleLocation(moduleNode.value)
  255. }, {})
  256. }
  257. if (arg.type === 'ArrayExpression') {
  258. const modulesNodes = arg.elements
  259. return transform(modulesNodes, (result, moduleNode, i) => {
  260. if (!moduleNode) return
  261. result[i] = getModuleLocation(moduleNode)
  262. }, {})
  263. }
  264. return {}
  265. }
  266. function getModulesLocationFromArrayConcat (arg) {
  267. // arg(CallExpression) =
  268. // Array([minId]).concat([<minId module>, <minId+1 module>, ...])
  269. //
  270. // Get the [minId] value from the Array() call first argument literal value
  271. const minId = arg.callee.object.arguments[0].value
  272. // The modules reside in the `concat()` function call arguments
  273. const modulesNodes = arg.arguments[0].elements
  274. return transform(modulesNodes, (result, moduleNode, i) => {
  275. if (!moduleNode) return
  276. result[i + minId] = getModuleLocation(moduleNode)
  277. }, {})
  278. }
  279. function getModuleLocation (node) {
  280. return { start: node.start, end: node.end }
  281. }