UNPKG

@modern-js/builder

Version:
165 lines (164 loc) • 6.3 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var fileSize_exports = {}; __export(fileSize_exports, { builderPluginFileSize: () => builderPluginFileSize, filterAsset: () => filterAsset }); module.exports = __toCommonJS(fileSize_exports); var import_path = __toESM(require("path")); var import_chalk = __toESM(require("@modern-js/utils/chalk")); var import_builder_shared = require("@modern-js/builder-shared"); const filterAsset = (asset) => !/\.map$/.test(asset) && !/\.LICENSE\.txt$/.test(asset); const getAssetColor = (size) => { if (size > 300 * 1e3) { return import_chalk.default.bold.red; } if (size > 100 * 1e3) { return import_chalk.default.yellow; } return import_chalk.default.green; }; async function printHeader(longestFileLength, longestLabelLength) { const longestLengths = [ longestFileLength, longestLabelLength ]; const headerRow = [ "File", "Size", "Gzipped" ].reduce((prev, cur, index) => { const length = longestLengths[index]; let curLabel = cur; if (length) { curLabel = cur.length < length ? cur + " ".repeat(length - cur.length) : cur; } return `${prev + curLabel} `; }, " "); import_builder_shared.logger.log(import_chalk.default.bold.blue(headerRow)); } async function printFileSizes(stats, distPath) { const { fs, filesize, gzipSize, stripAnsi } = await Promise.resolve().then(() => __toESM(require("@modern-js/utils"))); const formatAsset = (asset) => { const fileName = asset.name.split("?")[0]; const contents = fs.readFileSync(import_path.default.join(distPath, fileName)); const size = contents.length; const gzippedSize = gzipSize.sync(contents); return { size, folder: import_path.default.join(import_path.default.basename(distPath), import_path.default.dirname(fileName)), name: import_path.default.basename(fileName), gzippedSize, sizeLabel: filesize(size, { round: 1 }), gzipSizeLabel: getAssetColor(gzippedSize)(filesize(gzippedSize, { round: 1 })) }; }; const multiStats = "stats" in stats ? stats.stats : [ stats ]; const assets = multiStats.map((stats2) => { const origin = stats2.toJson({ all: false, assets: true, cachedAssets: true, groupAssetsByInfo: false, groupAssetsByPath: false, groupAssetsByChunk: false, groupAssetsByExtension: false, groupAssetsByEmitStatus: false }); const filteredAssets = origin.assets.filter((asset) => filterAsset(asset.name)); return filteredAssets.map(formatAsset); }).reduce((single, all) => all.concat(single), []); if (assets.length === 0) { return; } assets.sort((a, b) => b.size - a.size); const longestLabelLength = Math.max(...assets.map((a) => stripAnsi(a.sizeLabel).length)); const longestFileLength = Math.max(...assets.map((a) => stripAnsi(a.folder + import_path.default.sep + a.name).length)); import_builder_shared.logger.info(`Production file sizes: `); printHeader(longestFileLength, longestLabelLength); let totalSize = 0; let totalGzipSize = 0; assets.forEach((asset) => { let { sizeLabel } = asset; const { name, folder, gzipSizeLabel } = asset; const fileNameLength = stripAnsi(folder + import_path.default.sep + name).length; const sizeLength = stripAnsi(sizeLabel).length; totalSize += asset.size; totalGzipSize += asset.gzippedSize; if (sizeLength < longestLabelLength) { const rightPadding = " ".repeat(longestLabelLength - sizeLength); sizeLabel += rightPadding; } let fileNameLabel = import_chalk.default.dim(asset.folder + import_path.default.sep) + import_chalk.default.cyan(asset.name); if (fileNameLength < longestFileLength) { const rightPadding = " ".repeat(longestFileLength - fileNameLength); fileNameLabel += rightPadding; } import_builder_shared.logger.log(` ${fileNameLabel} ${sizeLabel} ${gzipSizeLabel}`); }); const totalSizeLabel = `${import_chalk.default.bold.blue("Total size:")} ${filesize(totalSize, { round: 1 })}`; const gzippedSizeLabel = `${import_chalk.default.bold.blue("Gzipped size:")} ${filesize(totalGzipSize, { round: 1 })}`; import_builder_shared.logger.log(` ${totalSizeLabel} ${gzippedSizeLabel} `); } const builderPluginFileSize = () => ({ name: "builder-plugin-file-size", setup(api) { api.onAfterBuild(async ({ stats }) => { const config = api.getNormalizedConfig(); if (config.performance.printFileSize && stats) { try { await printFileSizes(stats, api.context.distPath); } catch (err) { import_builder_shared.logger.error("Failed to print file size."); import_builder_shared.logger.error(err); } } }); } }); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { builderPluginFileSize, filterAsset });