UNPKG

next-bundle-analyzer

Version:
76 lines (72 loc) 3.53 kB
'use strict'; var node_fs = require('node:fs'); var path = require('node:path'); var open = require('open'); var analyzer = require('webpack-bundle-analyzer/lib/analyzer'); var constants = require('./constants.js'); var filterObject = require('./utils/filterObject.js'); var getCommonChunks = require('./utils/getCommonChunks.js'); var getMetadata = require('./utils/getMetadata.js'); var getPages = require('./utils/getPages.js'); var saveReport = require('./utils/saveReport.js'); var updateGroups = require('./utils/updateGroups.js'); const templatePath = path.join(__dirname, '../client/client.html'); class NextBundleAnalyzerPlugin { constructor(options) { this.options = options; } apply(compiler) { if (!this.options.enabled) { return; } compiler.hooks.done.tapPromise(constants.PLUGIN_NAME, async (stats) => { var _a, _b; const { outputPath } = compiler; const buildManifestPath = path.join(outputPath, 'build-manifest.json'); const { format, reportDir, reportFilename } = this.options; try { const useBuildManifest = node_fs.existsSync(buildManifestPath); const statsJson = stats.toJson(); const chunks = analyzer.getViewerData(statsJson, outputPath); const metadata = getMetadata.getMetadata(); updateGroups.updateGroups(chunks, statsJson); let commonChunks; let pages; if (useBuildManifest) { const buildManifest = require(buildManifestPath); commonChunks = getCommonChunks.getCommonChunks(buildManifest); pages = getPages.getPages(buildManifest, chunks, commonChunks); } const buildStats = { chunks, commonChunks, metadata, pages, }; if (format.includes('html')) { const { html } = this.options; const reportPath = path.join(outputPath, reportDir, `${reportFilename}.html`); const template = await node_fs.promises.readFile(templatePath, 'utf8'); const title = `${(_a = metadata.project) !== null && _a !== void 0 ? _a : 'Bundle'} ${metadata.date}`; const content = template .replace(constants.DATA_PLACEHOLDER, JSON.stringify(buildStats)) .replace(constants.TITLE_PLACEHOLDER, title); await saveReport.saveReport('html', reportPath, content); if (html.open) { await open(reportPath); } } if (format.includes('json')) { const { json } = this.options; const reportPath = path.join(outputPath, reportDir, `${reportFilename}.json`); await saveReport.saveReport('json', reportPath, JSON.stringify(filterObject.filterObject(buildStats, json.filter))); } } catch (error) { console.error(error); throw new Error(`${constants.PLUGIN_NAME}: unable to generate build stats: ${(_b = error === null || error === void 0 ? void 0 : error.stack) !== null && _b !== void 0 ? _b : error}`); } }); } } exports.NextBundleAnalyzerPlugin = NextBundleAnalyzerPlugin;