Skip to content

Commit

Permalink
feat: 🎸 report size (#335)
Browse files Browse the repository at this point in the history
* feat: 🎸 report size
  • Loading branch information
maoxiaoke authored Apr 25, 2022
1 parent c965e9f commit f398268
Show file tree
Hide file tree
Showing 18 changed files with 485 additions and 390 deletions.
2 changes: 1 addition & 1 deletion examples/package/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default defineConfig({
}],
// './plugin.js',
],
sourceMaps: 'inline',
sourceMaps: true,
define: {
__buildVersion: '0.1.2',
__buildNumber: 15,
Expand Down
2 changes: 1 addition & 1 deletion examples/package/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"default": "./es/index.js"
},
"scripts": {
"build": "CONSOLA_LEVEL=4 ice-pkg build",
"build": "ice-pkg build",
"start": "CONSOLA_LEVEL=4 ice-pkg start",
"help": "ice-pkg --help",
"test": "echo \"Error: no test specified\" && exit 1"
Expand Down
1 change: 1 addition & 0 deletions packages/pkg/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"escape-string-regexp": "^5.0.0",
"fs-extra": "^10.0.0",
"globby": "^11.0.4",
"gzip-size": "^7.0.0",
"magic-string": "^0.25.7",
"picocolors": "^1.0.0",
"postcss": "^8.4.6",
Expand Down
1 change: 1 addition & 0 deletions packages/pkg/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export default async (context: PkgContext) => {
config: configs,
});

// @ts-ignore fixme
const normalizedConfigs = configs.map((config) => mergeConfigOptions(config, context));

try {
Expand Down
28 changes: 24 additions & 4 deletions packages/pkg/src/buildAll.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,39 @@

import fs from 'fs-extra';
import { performance } from 'perf_hooks';
import { reportSize } from './helpers/reportSize.js';
import runTransform from './loaders/transform.js';
import runBundle from './loaders/bundle.js';
import { createLogger } from './helpers/logger.js';
import { timeFrom } from './utils.js';

import type { PkgContext, TaskConfig } from './types.js';
import type { PkgContext, TaskLoaderConfig, OutputFile } from './types.js';

export const buildAll = async (cfgArrs: TaskConfig[], ctx: PkgContext) => {
export const buildAll = async (cfgArrs: TaskLoaderConfig[], ctx: PkgContext) => {
for (let c = 0; c < cfgArrs.length; ++c) {
const { type } = cfgArrs[c];

let outputFiles: OutputFile[] = [];
if (type === 'bundle') {
await runBundle(cfgArrs[c]);
outputFiles = await runBundle(cfgArrs[c]);
}

if (type === 'transform') {
await runTransform(cfgArrs[c], ctx);
outputFiles = await runTransform(cfgArrs[c], ctx);
}

const reportSizeStart = performance.now();
if (ctx.command === 'build') {
reportSize(outputFiles.reduce((pre, chunk) => {
return {
...pre,
[chunk.filename]: chunk.code ? chunk.code : fs.readFileSync(chunk.dest),
};
}, ({} as any)));
}

const logger = createLogger('report-size');
logger.debug(`ReportSize consume ${timeFrom(reportSizeStart)}`);
}
};

11 changes: 6 additions & 5 deletions packages/pkg/src/helpers/getSwcConfig.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { stringifyObject } from '../utils.js';
import { TaskName } from '../types.js';

import type { UserConfig, TaskName } from '../types.js';
import type { UserConfig } from '../types.js';
import type { Config, ModuleConfig } from '@swc/core';

export const getBundleSwcConfig = (userConfig: UserConfig, taskName: TaskName): Config => {
const define = stringifyObject(userConfig?.define ?? {});

const target = taskName === 'pkg-dist-es2017' ? 'es2017' : 'es5';
const target = taskName === TaskName.BUNDLE_ES2017 ? 'es2017' : 'es5';

const browserTargets = taskName === 'pkg-dist-es2017' ? {
const browserTargets = taskName === TaskName.BUNDLE_ES2017 ? {
// https://github.com/ice-lab/ice-next/issues/54#issuecomment-1083263523
chrome: 61,
safari: 10.1,
Expand Down Expand Up @@ -52,11 +53,11 @@ export const getTransformSwcConfig = (userConfig: UserConfig, taskName: TaskName
const sourceMaps = userConfig?.sourceMaps;
const define = stringifyObject(userConfig?.define ?? {});

const module: ModuleConfig = taskName === 'pkg-cjs'
const module: ModuleConfig = taskName === TaskName.TRANSFORM_CJS
? { type: 'commonjs' }
: undefined;

const target = taskName === 'pkg-es2017' ? 'es2017' : 'es5';
const target = taskName === TaskName.TRANSFORM_ES2017 ? 'es2017' : 'es5';

return {
jsc: {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { join } from 'path';
import { isDirectory, isFile } from '../utils.js';
import { TaskName } from '../types.js';

const DEFAULT_ENTRY_DIR = 'src';
const DEFAULT_ENTRY_FILE = [
Expand Down Expand Up @@ -37,3 +38,10 @@ export const getEntryDir = (rootDir: string) => {

throw new Error(`Failed to resolve ${defaultEntryDir} as entry directory`);
};

export const getOutputDir = (rootDir: string, taskName: TaskName) => {
if (taskName.includes('transform')) {
return join(rootDir, taskName.split('-')[1]);
}
return join(rootDir, 'dist');
};
22 changes: 12 additions & 10 deletions packages/pkg/src/helpers/mergeConfigOptions.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { join } from 'path';
import deepmerge from 'deepmerge';
import { getEntryDir, getEntryFile } from './getTaskEntry.js';
import { getEntryDir, getEntryFile, getOutputDir } from './getTaskIO.js';
import { getBundleSwcConfig, getTransformSwcConfig } from './getSwcConfig.js';
import { normalizeRollupConfig } from './normalizeRollupConfig.js';

import type { PkgContext, TaskConfig, PkgTaskConfig, TaskName } from '../types.js';
import type { PkgContext, TaskLoaderConfig, PkgTaskConfig } from '../types.js';

export const mergeConfigOptions = (
cfg: PkgTaskConfig,
ctx: PkgContext,
): TaskConfig => {
): TaskLoaderConfig => {
const { rootDir, userConfig } = ctx;
const { config: taskConfig, name: taskName } = cfg;
const normalizedConfig = { ...taskConfig };
Expand All @@ -21,14 +20,14 @@ export const mergeConfigOptions = (
isBundleTask ? getEntryFile(rootDir) : getEntryDir(rootDir)
);

// Configure task outputDir(Taskname 以 pkg-[cjs|esm|es2017 命名])
normalizedConfig.outputDir = outputDir || join(rootDir, taskName.split('-')[1]);
// Configure task outputDir
normalizedConfig.outputDir = outputDir || getOutputDir(rootDir, taskName);

// Configure swcOptions
const swcOptionOverride = deepmerge(
isBundleTask
? getBundleSwcConfig(userConfig as any, taskName as TaskName)
: getTransformSwcConfig(userConfig as any, taskName as TaskName),
? getBundleSwcConfig(userConfig, taskName)
: getTransformSwcConfig(userConfig, taskName),
swcCompileOptions,
);

Expand All @@ -38,11 +37,14 @@ export const mergeConfigOptions = (
const [resolvedPlugins, resolvedRollupOption] = normalizeRollupConfig(
normalizedConfig,
ctx,
taskName as TaskName,
taskName,
);

normalizedConfig.rollupPlugins = resolvedPlugins;
normalizedConfig.rollupOptions = resolvedRollupOption;

return normalizedConfig;
return {
...normalizedConfig,
name: taskName,
};
};
5 changes: 3 additions & 2 deletions packages/pkg/src/helpers/normalizeRollupConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import dtsPlugin from '../plugins/dts.js';
import minify from '../plugins/minify.js';
import babelPlugin from '../plugins/babel.js';
import { builtinNodeModules } from './builtinModules.js';
import { TaskName } from '../types.js';

import type { Plugin as RollupPlugin, RollupOptions, OutputOptions } from 'rollup';
import type { TaskConfig, PkgContext, TaskName, UserConfig } from '../types.js';
import type { TaskConfig, PkgContext, UserConfig } from '../types.js';

interface PkgJson {
name: string;
Expand Down Expand Up @@ -172,7 +173,7 @@ export const normalizeRollupConfig = (
userConfig,
pkg: pkg as PkgJson,
outputDir: cfg.outputDir,
isES2017: taskName === 'pkg-dist-es2017',
isES2017: taskName === TaskName.BUNDLE_ES2017,
}),
},
cfg.rollupOptions || {},
Expand Down
32 changes: 32 additions & 0 deletions packages/pkg/src/helpers/reportSize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import consola from 'consola';
import picocolors from 'picocolors';
import { gzipSizeSync } from 'gzip-size';

const UNIT = ['B', 'KB', 'MB', 'GB', 'TB'];

const prettifySize = (bytes: number): string => {
if (bytes === 0) return '0 B';

const exp = Math.floor(Math.log2(bytes) / 10);
return `${(bytes / Math.pow(1024, exp)).toFixed(2)} ${UNIT[exp]}`;
};

const findMaxLength = (names: string[]) => {
return names.map((name) => name.length).sort((a, b) => b - a)[0];
};

export const reportSize = (
files: {
[name: string]: string;
},
) => {
const names = Object.keys(files);
const maxLen = findMaxLength(names);
const padLength = maxLen > 30 ? (maxLen + 2) : 30;

names.forEach((name) => {
const rawSize = prettifySize(files[name].length);
const gzipSize = prettifySize(gzipSizeSync(files[name]));
consola.info(`${name.padStart(padLength, ' ')}: ${picocolors.green('raw')} ${rawSize} ${picocolors.cyan('gzip')} ${gzipSize}`);
});
};
24 changes: 16 additions & 8 deletions packages/pkg/src/loaders/bundle.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,38 @@
import * as rollup from 'rollup';
import { performance } from 'perf_hooks';
import { toArray } from '../utils.js';
import { toArray, timeFrom } from '../utils.js';
import { createLogger } from '../helpers/logger.js';

import type { TaskConfig } from '../types.js';
import type { TaskLoaderConfig, OutputFile } from '../types.js';

export default async (cfg: TaskConfig): Promise<boolean> => {
const logger = createLogger('bundle');
export default async (cfg: TaskLoaderConfig): Promise<OutputFile[]> => {
const logger = createLogger(cfg.name);

const bundleStart = performance.now();

const rollupOption = cfg.rollupOptions;

logger.info('Build start...');
logger.debug('Build start...');
const bundle = await rollup.rollup(rollupOption);

const outputs = toArray(rollupOption.output);
const outputChunks: OutputFile[] = [];

for (let o = 0; o < outputs.length; ++o) {
// eslint-disable-next-line no-await-in-loop
await bundle.write(outputs[o]);
const writeResult = await bundle.write(outputs[o]);

writeResult.output.forEach((chunk) => {
outputChunks.push({
filename: chunk.fileName,
code: chunk.type === 'chunk' ? chunk.code : chunk.source,
});
});
}

await bundle.close();

logger.info(`⚡️ Build success in ${(performance.now() - bundleStart).toFixed(2)}ms`);
logger.info(`⚡️ Build success in ${timeFrom(bundleStart)}`);

return true;
return outputChunks;
};
32 changes: 8 additions & 24 deletions packages/pkg/src/loaders/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,17 @@ import { createPluginContainer } from '../helpers/pluginContainer.js';
import { isObject, isDirectory, timeFrom } from '../utils.js';
import { createLogger } from '../helpers/logger.js';

import type { PkgContext, TaskConfig } from '../types.js';
import type { PkgContext, TaskLoaderConfig, OutputFile } from '../types.js';
import type { SourceMapInput } from 'rollup';

export interface File {
// globby parsed path, which is relative
filePath: string;
// absolute path
absolutePath: string;
// extension
// ext: 'jsx' | 'js' | 'ts' | 'tsx' | 'mjs' | 'png' | 'scss' | 'less' | 'css' | 'png' | 'jpg';
ext: string;
// where to store target files
dest?: string;
// parsed code
code?: string;
// source map
map?: string | SourceMapInput;
}

export default async function runTransform(cfg: TaskConfig, ctx: PkgContext) {
const { rootDir, userConfig } = ctx;
export default async function runTransform(cfg: TaskLoaderConfig, ctx: PkgContext) {
const { rootDir, userConfig, command } = ctx;
const { outputDir, entry, rollupPlugins } = cfg;

const logger = createLogger('transform');
const logger = createLogger(cfg.name);
const entryDir = entry;

let files: File[];
let files: OutputFile[];

if (isDirectory(entry)) {
files =
Expand Down Expand Up @@ -66,7 +50,7 @@ export default async function runTransform(cfg: TaskConfig, ctx: PkgContext) {

const transformStart = performance.now();

logger.info('Build start...');
logger.debug('Build start...');

// @ts-ignore FIXME: ignore
await container.buildStart(cfg);
Expand Down Expand Up @@ -143,7 +127,7 @@ export default async function runTransform(cfg: TaskConfig, ctx: PkgContext) {

await container.close();

logger.info(`⚡️ Build success in ${(performance.now() - transformStart).toFixed(2)}ms`);
logger.info(`⚡️ Build success in ${timeFrom(transformStart)}`);

return files;
return files.map((file) => ({ ...file, filename: relative(outputDir, file.dest) }));
}
5 changes: 2 additions & 3 deletions packages/pkg/src/plugins/swc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ import { isTypescriptOnly } from '../helpers/suffix.js';
import { isDirectory, scriptsFilter } from '../utils.js';

import type { Options as swcCompileOptions, Config } from '@swc/core';
import type { RollupPluginFn } from '../types.js';
import type { File } from '../loaders/transform.js';
import type { RollupPluginFn, OutputFile } from '../types.js';

const normalizeSwcConfig = (
file: File,
file: OutputFile,
mergeOptions?: swcCompileOptions,
): swcCompileOptions => {
const { filePath, ext } = file;
Expand Down
5 changes: 3 additions & 2 deletions packages/pkg/src/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import { createWatcher } from './helpers/watcher.js';
import { debouncePromise } from './utils.js';
import { buildAll } from './buildAll.js';

import type { PkgContext, TaskConfig } from './types.js';
import type { PkgContext, TaskLoaderConfig } from './types.js';

const debouncedBuildAll = debouncePromise(
async (cfgArrs: TaskConfig[], ctx: PkgContext) => {
async (cfgArrs: TaskLoaderConfig[], ctx: PkgContext) => {
await buildAll(cfgArrs, ctx);
},
100,
Expand All @@ -33,6 +33,7 @@ export default async (context: PkgContext) => {
config: configs,
});

// @ts-ignore fixme
const normalizedConfigs = configs.map((config) => mergeConfigOptions(config, context));

await buildAll(normalizedConfigs, context);
Expand Down
Loading

0 comments on commit f398268

Please sign in to comment.