Skip to content

Commit

Permalink
feat(module-tools): improve logs in watch mode (#4729)
Browse files Browse the repository at this point in the history
  • Loading branch information
chenjiahan authored Sep 27, 2023
1 parent e3f05c6 commit bbc65b8
Show file tree
Hide file tree
Showing 14 changed files with 64 additions and 110 deletions.
7 changes: 7 additions & 0 deletions .changeset/honest-wasps-remain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@modern-js/module-tools': patch
---

feat(module-tools): improve logs in watch mode

feat(module-tools): 优化 watch 模式下的日志
11 changes: 3 additions & 8 deletions packages/solutions/module-tools/src/builder/build.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { slash, logger, fs } from '@modern-js/utils';
import { withLogTitle } from '../utils';
import type {
BuildCommandOptions,
BaseBuildConfig,
Expand Down Expand Up @@ -126,14 +127,8 @@ export const buildLib = async (
addOutputChunk(compiler.outputChunk, root, buildType === 'bundle');

if (watch) {
const { watchSectionTitle } = await import('../utils/log');
const { SectionTitleStatus } = await import('../constants/log');
const titleText = `[${
buildType === 'bundle' ? 'Bundle' : 'Bundleless'
}: ${format}_${target}]`;

logger.info(
await watchSectionTitle(titleText, SectionTitleStatus.Success),
logger.success(
withLogTitle(buildType, `Build ${format},${target} files`),
);
}
} catch (e: any) {
Expand Down
22 changes: 3 additions & 19 deletions packages/solutions/module-tools/src/builder/copy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from 'path';
import { watch, fs, logger, globby, fastGlob } from '@modern-js/utils';
import { watch, fs, chalk, logger, globby, fastGlob } from '@modern-js/utils';
import type { CopyOptions, CopyPattern } from '../types/config/copy';
import type { BaseBuildConfig } from '../types/config';
import pMap from '../../compiled/p-map';
Expand Down Expand Up @@ -151,10 +151,6 @@ export const watchCopyFiles = async (
) => {
debug('watchMap', watchMap);

const { SectionTitleStatus, CopyLogPrefix } = await import(
'../constants/log'
);
const { watchSectionTitle } = await import('../utils/log');
const watchList = Array.from(watchMap.keys());

debug('watchList', watchList);
Expand All @@ -169,13 +165,7 @@ export const watchCopyFiles = async (

if (changeType === 'unlink') {
fs.remove(result);
logger.log(
await watchSectionTitle(
CopyLogPrefix,
SectionTitleStatus.Log,
`${formatFilePath} removed`,
),
);
logger.info(`Copied file removed: ${chalk.dim(formatFilePath)}`);
return;
}

Expand All @@ -185,13 +175,7 @@ export const watchCopyFiles = async (
await fs.copy(changedFilePath, result);
}

logger.log(
await watchSectionTitle(
CopyLogPrefix,
SectionTitleStatus.Log,
`${formatFilePath} changed`,
),
);
logger.info(`Copy file: ${chalk.dim(formatFilePath)}`);
});
};

Expand Down
17 changes: 3 additions & 14 deletions packages/solutions/module-tools/src/builder/dts/rollup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import type {
} from '../../types';
import jsonPlugin from '../../../compiled/@rollup/plugin-json';
import dtsPlugin from '../../../compiled/rollup-plugin-dts';
import { mapValue, transformUndefineObject } from '../../utils';
import { mapValue, transformUndefineObject, withLogTitle } from '../../utils';

export type { RollupWatcher };

Expand Down Expand Up @@ -113,27 +113,16 @@ export const runRollup = async (
};
if (watch) {
const { watch } = await import('../../../compiled/rollup');
const { watchSectionTitle } = await import('../../utils');
const { SectionTitleStatus, BundleDtsLogPrefix } = await import(
'../../constants/log'
);
const runner = api.useHookRunners();
const watcher = watch({
...inputConfig,
plugins: inputConfig.plugins,
output: outputConfig,
}).on('event', async event => {
if (event.code === 'START') {
logger.info(
await watchSectionTitle(BundleDtsLogPrefix, SectionTitleStatus.Log),
);
logger.info(withLogTitle('bundle', 'Start build types...'));
} else if (event.code === 'BUNDLE_END') {
logger.info(
await watchSectionTitle(
BundleDtsLogPrefix,
SectionTitleStatus.Success,
),
);
logger.success(withLogTitle('bundle', 'Build types'));
runner.buildWatchDts({ buildType: 'bundle' });
} else if (event.code === 'ERROR') {
// this is dts rollup plugin bug, error not complete message
Expand Down
20 changes: 11 additions & 9 deletions packages/solutions/module-tools/src/builder/dts/tsc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,15 @@ import {
getTscBinPath,
printOrThrowDtsErrors,
resolveAlias,
watchSectionTitle,
addDtsFiles,
writeDtsFiles,
addBannerAndFooter,
withLogTitle,
} from '../../utils';
import {
BundlelessDtsLogPrefix,
SectionTitleStatus,
} from '../../constants/log';
import { watchDoneText } from '../../constants/dts';

export const removeTscLogTime = (log: string) => log.replace(/\[.*\]\s/, '');

const resolveLog = async (
childProgress: ChildProcess,
options: {
Expand All @@ -38,10 +36,14 @@ const resolveLog = async (
*/
childProgress.stdout?.on('data', async data => {
if (watch) {
logger.info(
await watchSectionTitle(BundlelessDtsLogPrefix, SectionTitleStatus.Log),
);
logger.info(data.toString());
const lines = (data.toString() as string)
.split('\n')
// remove empty lines
.filter(line => line.trim() !== '')
// add tsc prefix, remove time prefix
.map(line => withLogTitle('tsc', removeTscLogTime(line)));
logger.info(lines.join('\n'));

if (data.toString().includes(watchDoneText)) {
await watchFn();
}
Expand Down
13 changes: 9 additions & 4 deletions packages/solutions/module-tools/src/builder/esbuild/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
} from 'esbuild';
import * as tapable from 'tapable';
import { FSWatcher, chalk, logger, fs, lodash } from '@modern-js/utils';
import { withLogTitle } from '../../utils';
import {
BaseBuildConfig,
BuilderHooks,
Expand Down Expand Up @@ -269,7 +270,7 @@ export class EsbuildCompiler implements ICompiler {
}
}

async reBuild(type: 'link' | 'change') {
async reBuild(type: 'link' | 'change', config: BaseBuildConfig) {
const { instance } = this;
try {
const start = Date.now();
Expand All @@ -278,9 +279,13 @@ export class EsbuildCompiler implements ICompiler {
} else {
this.result = await instance?.rebuild();
}
logger.info(
chalk.green`Rebuild Successfully in ${Date.now() - start}ms`,
chalk.yellow`Rebuild Count: ${++this.reBuildCount}`,

const time = chalk.gray(`(${Date.now() - start}ms)`);
logger.success(
withLogTitle(
config.buildType,
`Build ${config.format},${config.target} files ${time}`,
),
);
} catch (error: any) {
logger.error(error);
Expand Down
16 changes: 4 additions & 12 deletions packages/solutions/module-tools/src/builder/esbuild/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ export const initWatcher = (compiler: ICompiler) => {
needReRun = true;
} else {
running = true;
await compiler.reBuild('link');
await compiler.reBuild('link', config);
running = false;
if (needReRun) {
needReRun = false;
await compiler.reBuild('link');
await compiler.reBuild('link', config);
}
}
}
Expand All @@ -68,18 +68,10 @@ export const initWatcher = (compiler: ICompiler) => {
watchedFiles,
} = compiler;
if (watchedFiles.has(path.resolve(root, filePath))) {
logger.info(`${chalk.underline(filePath)} changed`);
const { watchSectionTitle } = await import('../../utils');
const { SectionTitleStatus } = await import('../../constants/log');
const titleText = `[${
config.buildType === 'bundle' ? 'Bundle' : 'Bundleless'
}:${config.format}_${config.target}]`;

logger.info(await watchSectionTitle(titleText, SectionTitleStatus.Log));

logger.info(`File changed: ${chalk.dim(filePath)}`);
const runner = api.useHookRunners();
runner.buildWatchJs({ buildConfig: config });
await compiler.reBuild('change');
await compiler.reBuild('change', config);
}
};
watch.on('ready', () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/solutions/module-tools/src/builder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const run = async (
await clearDtsTemp();

if (watch) {
logger.info('Start build in watch mode...\n');
logger.info('Start build in watch mode...');
}

try {
Expand Down
9 changes: 0 additions & 9 deletions packages/solutions/module-tools/src/constants/log.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
export enum SectionTitleStatus {
Success,
Fail,
Log,
}

export const BundleDtsLogPrefix = '[Bundle:DTS]';
export const BundlelessDtsLogPrefix = '[Bundleless:DTS]';
export const CopyLogPrefix = '[Copy]';
export const buildSuccessText = 'Build succeed';

export const reportFile1LineText = 'Bundle Files';
Expand Down
2 changes: 1 addition & 1 deletion packages/solutions/module-tools/src/types/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export type Context = {
};

export interface ICompiler {
reBuild: (type: 'link' | 'change') => Promise<void>;
reBuild: (type: 'link' | 'change', config: BaseBuildConfig) => Promise<void>;
css_resolve: (id: string, dir: string) => string;
node_resolve: (id: string, dir: string, kind: ImportKind) => string;
init: () => Promise<void>;
Expand Down
18 changes: 3 additions & 15 deletions packages/solutions/module-tools/src/utils/log.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,4 @@
import { SectionTitleStatus } from '../constants/log';
import chalk from '@modern-js/utils/chalk';

export const watchSectionTitle = async (
str: string,
status: SectionTitleStatus,
detailLog?: string,
) => {
const { chalk } = await import('@modern-js/utils');
if (status === SectionTitleStatus.Success) {
return `${chalk.gray(str)} ${chalk.green('Successful')}`;
} else if (status === SectionTitleStatus.Fail) {
return `${chalk.gray(str)} ${chalk.red('Build Failed')}`;
}

return `${chalk.gray(str)} ${detailLog ? detailLog : 'Log:'}`;
};
export const withLogTitle = (titleText: string, message: string) =>
`${message} ${chalk.gray(`[${titleText}]`)}`;
4 changes: 2 additions & 2 deletions packages/solutions/module-tools/src/utils/print.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const printFileSize = () => {
};

export const printSucceed = (totalDuration: number) => {
const time = chalk.cyan(`${totalDuration / 1000}s`);
const time = chalk.cyan(`${(totalDuration / 1000).toFixed(1)}s`);
logger.info(`${buildSuccessText} in ${time}`);
};

Expand All @@ -86,7 +86,7 @@ const prettyBytes = (bytes: number) => {
}
const unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const exp = Math.floor(Math.log(bytes) / Math.log(1024));
return `${(bytes / Math.pow(1024, exp)).toFixed(2)} ${unit[exp]}`;
return `${(bytes / Math.pow(1024, exp)).toFixed(1)} ${unit[exp]}`;
};

const printBundleFiles = () => {
Expand Down
17 changes: 17 additions & 0 deletions packages/solutions/module-tools/tests/builder.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'path';
import { checkSwcHelpers } from '../src/utils';
import { removeTscLogTime } from '../src/builder/dts/tsc';

describe('utils: builder', () => {
it('checkSwcHelpers', async () => {
Expand All @@ -24,3 +25,19 @@ describe('utils: builder', () => {
expect(test2HappenError).toBeFalsy();
});
});

describe('utils: removeTscLogTime', () => {
it('should remove time from tsc logs correctly', () => {
expect(
removeTscLogTime(
'[\x1B[90m7:28:23 PM\x1B[0m] Starting compilation in watch mode...',
),
).toEqual('Starting compilation in watch mode...');

expect(
removeTscLogTime(
'[\x1B[90m7:28:24 PM\x1B[0m] Found 0 errors. Watching for file changes.',
),
).toEqual('Found 0 errors. Watching for file changes.');
});
});
16 changes: 0 additions & 16 deletions packages/solutions/module-tools/tests/log.test.ts

This file was deleted.

0 comments on commit bbc65b8

Please sign in to comment.