Spec-Zone.ru › webpack 4

Статистические данные

При компиляции исходного кода с помощью webpack пользователи могут сгенерировать файл JSON, содержащий статистику о модулях. Эту статистику можно использовать для анализа графа зависимостей приложения, а также для оптимизации скорости компиляции. Файл обычно генерируется следующей командой командной строки:

webpack --profile --json > compilation-stats.json

Флаг --json > compilation-stats.json указывает webpack на необходимость вывода файла compilation-stats.json, содержащего граф зависимостей и различные другие сведения о сборке. Обычно также добавляется флаг --profile, чтобы в каждый modules объект добавлялся раздел profile с модульной статистикой компиляции.

Структура

Общая структура выходного файла JSON довольно простая, но также есть несколько вложенных структур данных. Каждая вложенная структура имеет специальный раздел ниже, чтобы сделать этот документ более удобочитаемым. Обратите внимание, что вы можете перейти по ссылкам в структуре ниже, чтобы перейти к соответствующим разделам и документации:

{
  'version': '1.4.13', // Version of webpack used for the compilation
  'hash': '11593e3b3ac85436984a', // Compilation specific hash
  'time': 2469, // Compilation time in milliseconds
  'filteredModules': 0, // A count of excluded modules when exclude is passed to the toJson method
  'outputPath': '/', // path to webpack output directory
  'assetsByChunkName': {
    // Chunk name to emitted asset(s) mapping
    'main': 'web.js?h=11593e3b3ac85436984a',
    'named-chunk': 'named-chunk.web.js',
    'other-chunk': [
      'other-chunk.js',
      'other-chunk.css'
    ]
  },
  'assets': [
    // A list of asset objects
  ],
  'chunks': [
    // A list of chunk objects
  ],
  'modules': [
    // A list of module objects
  ],
  'errors': [
    // A list of error strings
  ],
  'warnings': [
    // A list of warning strings
  ]
}

Объекты активов

Каждый assets объект представляет собой файл output , выводимый из компиляции. Все они имеют похожую структуру:

{
  'chunkNames': [], // The chunks this asset contains
  'chunks': [ 10, 6 ], // The chunk IDs this asset contains
  'emitted': true, // Indicates whether or not the asset made it to the output directory
  'name': '10.web.js', // The output filename
  'size': 1058, // The size of the file in bytes
  'info': {
    'immutable': true, // A flag telling whether the asset can be long term cached (contains a hash)
    'size': 1058, // The size in bytes, only becomes available after asset has been emitted
    'development': true, // A flag telling whether the asset is only used for development and doesn't count towards user-facing assets
    'hotModuleReplacement': true // A flag telling whether the asset ships data for updating an existing application (HMR)
  }
}

Свойство info актива доступно с версии webpack v4.40.0

Объекты блоков

Каждый chunks объект представляет собой группу модулей, известную как блок. Каждый объект имеет следующую структуру:

{
  "entry": true, // Indicates whether or not the chunk contains the webpack runtime
  "files": [
    // An array of filename strings that contain this chunk
  ],
  "filteredModules": 0, // See the description in the top-level structure above
  "id": 0, // The ID of this chunk
  "initial": true, // Indicates whether this chunk is loaded on initial page load or on demand
  "modules": [
    // A list of module objects
    "web.js?h=11593e3b3ac85436984a"
  ],
  "names": [
    // An list of chunk names contained within this chunk
  ],
  "origins": [
    // See the description below...
  ],
  "parents": [], // Parent chunk IDs
  "rendered": true, // Indicates whether or not the chunk went through Code Generation
  "size": 188057 // Chunk size in bytes
}

Объект chunks также будет содержать список origins, описывающий происхождение данного блока. Каждый origins объект имеет следующую схему:

{
  "loc": "", // Lines of code that generated this chunk
  "module": "(webpack)\test\browsertest\lib\index.web.js", // Path to the module
  "moduleId": 0, // The ID of the module
  "moduleIdentifier": "(webpack)\test\browsertest\lib\index.web.js", // Path to the module
  "moduleName": "./lib/index.web.js", // Relative path to the module
  "name": "main", // The name of the chunk
  "reasons": [
    // A list of the same reasons found in module objects
  ]
}

Объекты модулей

Для чего нужны эти статистические данные без описания самих модулей компилируемого приложения? Каждый модуль в графе зависимостей представлен следующей структурой:

{
  "assets": [
    // A list of asset objects
  ],
  "built": true, // Indicates that the module went through Loaders, Parsing, and Code Generation
  "cacheable": true, // Whether or not this module is cacheable
  "chunks": [
    // IDs of chunks that contain this module
  ],
  "errors": 0, // Number of errors when resolving or processing the module
  "failed": false, // Whether or not compilation failed on this module
  "id": 0, // The ID of the module (analogous to module.id)
  "identifier": "(webpack)\test\browsertest\lib\index.web.js", // A unique ID used internally
  "name": "./lib/index.web.js", // Path to the actual file
  "optional": false, // All requests to this module are with try... catch blocks (irrelevant with ESM)
  "prefetched": false, // Indicates whether or not the module was prefetched
  "profile": {
    // Module specific compilation stats corresponding to the --profile flag (in milliseconds)
    "building": 73, // Loading and parsing
    "dependencies": 242, // Building dependencies
    "factory": 11 // Resolving dependencies
  },
  "reasons": [
    // See the description below...
  ],
  "size": 3593, // Estimated size of the module in bytes
  "source": "// Should not break it...
if(typeof...", // The stringified raw source
  "warnings": 0 // Number of warnings when resolving or processing the module
}

Каждый модуль также содержит список reasons объектов, описывающих причины включения этого модуля в граф зависимостей. Каждый "причина" похож на origins , приведенный выше в разделе объекты блоков:

{
  "loc": "33:24-93", // Lines of code that caused the module to be included
  "module": "./lib/index.web.js", // Relative path to the module based on context
  "moduleId": 0, // The ID of the module
  "moduleIdentifier": "(webpack)\test\browsertest\lib\index.web.js", // Path to the module
  "moduleName": "./lib/index.web.js", // A more readable name for the module (used for "pretty-printing")
  "type": "require.context", // The type of request used
  "userRequest": "../../cases" // Raw string used for the import or require request
}

Ошибки и предупреждения

Свойства errors и warnings каждый содержат список строк. Каждая строка содержит сообщение и стек вызовов:

../cases/parsing/browserify/index.js
Critical dependencies:
2:114-121 This seem to be a pre-built javascript file. Even while this is possible, it's not recommended. Try to require to original source to get better results.
 @ ../cases/parsing/browserify/index.js 2:114-121

Обратите внимание, что стеки вызовов удаляются, когда errorDetails: false передается в метод toJson. Параметр errorDetails по умолчанию установлен в true.

© JS Foundation and other contributors
Licensed under the Creative Commons Attribution License 4.0.
https://v4.webpack.js.org/api/stats

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API