Skip to content

Commit a09282b

Browse files
authored
refactor: replace chalk with nanocolors (#1685)
1 parent d4f92e2 commit a09282b

24 files changed

+104
-109
lines changed

.changeset/rare-lions-sneeze.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'@web/dev-server': patch
3+
'@web/dev-server-core': patch
4+
'@web/dev-server-rollup': patch
5+
'@web/test-runner': patch
6+
'@web/test-runner-core': patch
7+
---
8+
9+
Replace chalk with nanocolors

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
"husky": "^7.0.1",
6363
"lint-staged": "^11.1.1",
6464
"mocha": "^8.2.1",
65+
"nanocolors": "^0.1.6",
6566
"prettier": "^2.3.2",
6667
"prettier-plugin-package": "^1.3.0",
6768
"rimraf": "^3.0.2",

packages/dev-server-core/src/test-helpers.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import portfinder from 'portfinder';
22
import { expect } from 'chai';
3-
import chalk from 'chalk';
3+
import { green, red, yellow } from 'nanocolors';
44
import fetch, { RequestInit } from 'node-fetch';
55

66
import { DevServer } from './server/DevServer';
@@ -66,9 +66,7 @@ export async function fetchText(url: string, init?: RequestInit) {
6666

6767
export function expectIncludes(text: string, expected: string) {
6868
if (!text.includes(expected)) {
69-
throw new Error(
70-
chalk.red(`Expected "${chalk.yellow(expected)}" in string: \n\n${chalk.green(text)}`),
71-
);
69+
throw new Error(red(`Expected "${yellow(expected)}" in string: \n\n${green(text)}`));
7270
}
7371
}
7472

packages/dev-server-rollup/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
],
4949
"dependencies": {
5050
"@web/dev-server-core": "^0.3.3",
51-
"chalk": "^4.1.0",
51+
"nanocolors": "^0.1.6",
5252
"parse5": "^6.0.1",
5353
"rollup": "^2.56.2",
5454
"whatwg-url": "^9.0.0"

packages/dev-server-rollup/src/rollupAdapter.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import {
1919
import { parse as parseHtml, serialize as serializeHtml } from 'parse5';
2020
import { CustomPluginOptions, Plugin as RollupPlugin, TransformPluginContext } from 'rollup';
2121
import { InputOptions } from 'rollup';
22-
import { red, cyanBright } from 'chalk';
22+
import { red, cyan } from 'nanocolors';
2323

2424
import { toBrowserPath, isAbsoluteFilePath, isOutsideRootDir } from './utils';
2525
import { createRollupPluginContextAdapter } from './createRollupPluginContextAdapter';
@@ -172,7 +172,7 @@ export function rollupAdapter(
172172
!['/', './', '../'].some(prefix => resolvableImport.startsWith(prefix)) &&
173173
adapterOptions.throwOnUnresolvedImport
174174
) {
175-
const errorMessage = red(`Could not resolve import ${cyanBright(`"${source}"`)}.`);
175+
const errorMessage = red(`Could not resolve import ${cyan(`"${source}"`)}.`);
176176
if (
177177
typeof code === 'string' &&
178178
typeof column === 'number' &&
@@ -222,7 +222,7 @@ export function rollupAdapter(
222222
if (dirUpStrings.length === 0 || dirUpStrings.some(str => !['..', ''].includes(str))) {
223223
// we expect the relative part to consist of only ../ or ..\\
224224
const errorMessage =
225-
red(`\n\nResolved ${cyanBright(source)} to ${cyanBright(resolvedImportPath)}.\n\n`) +
225+
red(`\n\nResolved ${cyan(source)} to ${cyan(resolvedImportPath)}.\n\n`) +
226226
red(
227227
'This path could not be converted to a browser path. Please file an issue with a reproduction.',
228228
);

packages/dev-server/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,12 @@
6262
"@web/dev-server-core": "^0.3.15",
6363
"@web/dev-server-rollup": "^0.3.9",
6464
"camelcase": "^6.2.0",
65-
"chalk": "^4.1.0",
6665
"command-line-args": "^5.1.1",
6766
"command-line-usage": "^6.1.1",
6867
"debounce": "^1.2.0",
6968
"deepmerge": "^4.2.2",
7069
"ip": "^1.1.5",
70+
"nanocolors": "^0.1.6",
7171
"open": "^8.0.2",
7272
"portfinder": "^1.0.28"
7373
},

packages/dev-server/src/logger/DevServerLogger.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Logger, PluginSyntaxError } from '@web/dev-server-core';
22
import { codeFrameColumns } from '@babel/code-frame';
33
import path from 'path';
4-
import chalk from 'chalk';
4+
import { red, cyan } from 'nanocolors';
55

66
export class DevServerLogger implements Logger {
77
private debugLogging: boolean;
@@ -48,9 +48,7 @@ export class DevServerLogger implements Logger {
4848
const result = codeFrameColumns(code, { start: { line, column } }, { highlightCode: false });
4949

5050
const relativePath = path.relative(process.cwd(), filePath);
51-
console.error(
52-
chalk.red(`Error while transforming ${chalk.cyanBright(relativePath)}: ${message}\n`),
53-
);
51+
console.error(red(`Error while transforming ${cyan(relativePath)}: ${message}\n`));
5452
console.error(highlightedResult);
5553
console.error('');
5654

packages/dev-server/src/logger/logStartMessage.ts

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { DevServerConfig } from '../config/DevServerConfig';
22
import { Logger } from '@web/dev-server-core';
33
import ip from 'ip';
4-
import chalk from 'chalk';
4+
import { bold, cyan, white } from 'nanocolors';
55

66
const createAddress = (config: DevServerConfig, host: string, path: string) =>
77
`http${config.http2 ? 's' : ''}://${host}:${config.port}${path}`;
@@ -10,9 +10,7 @@ function logNetworkAddress(config: DevServerConfig, logger: Logger, openPath: st
1010
try {
1111
const address = ip.address();
1212
if (typeof address === 'string') {
13-
logger.log(
14-
`${chalk.white('Network:')} ${chalk.cyanBright(createAddress(config, address, openPath))}`,
15-
);
13+
logger.log(`${white('Network:')} ${cyan(createAddress(config, address, openPath))}`);
1614
}
1715
} catch {
1816
//
@@ -26,14 +24,12 @@ export function logStartMessage(config: DevServerConfig, logger: Logger) {
2624
openPath = `/${openPath}`;
2725
}
2826

29-
logger.log(chalk.bold('Web Dev Server started...'));
27+
logger.log(bold('Web Dev Server started...'));
3028
logger.log('');
3129

3230
logger.group();
33-
logger.log(`${chalk.white('Root dir:')} ${chalk.cyanBright(config.rootDir)}`);
34-
logger.log(
35-
`${chalk.white('Local:')} ${chalk.cyanBright(createAddress(config, prettyHost, openPath))}`,
36-
);
31+
logger.log(`${white('Root dir:')} ${cyan(config.rootDir)}`);
32+
logger.log(`${white('Local:')} ${cyan(createAddress(config, prettyHost, openPath))}`);
3733
logNetworkAddress(config, logger, openPath);
3834
logger.groupEnd();
3935
logger.log('');

packages/test-runner-core/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,6 @@
5959
"@types/istanbul-reports": "^3.0.0",
6060
"@web/browser-logs": "^0.2.1",
6161
"@web/dev-server-core": "^0.3.12",
62-
"chalk": "^4.1.0",
6362
"chokidar": "^3.4.3",
6463
"cli-cursor": "^3.1.0",
6564
"co-body": "^6.1.0",
@@ -72,6 +71,7 @@
7271
"istanbul-lib-report": "^3.0.0",
7372
"istanbul-reports": "^3.0.2",
7473
"log-update": "^4.0.0",
74+
"nanocolors": "^0.1.6",
7575
"nanoid": "^3.1.25",
7676
"open": "^8.0.2",
7777
"picomatch": "^2.2.2",

packages/test-runner-core/src/cli/TestRunnerCli.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { codeFrameColumns } from '@babel/code-frame';
22
import path from 'path';
3-
import chalk from 'chalk';
3+
import { bold, cyan, red } from 'nanocolors';
44
import openBrowser from 'open';
55

66
import { writeCoverageReport } from './writeCoverageReport';
@@ -85,7 +85,7 @@ export class TestRunnerCli {
8585
}
8686

8787
if (this.config.staticLogging || !this.terminal.isInteractive) {
88-
this.logger.log(chalk.bold(`Running ${this.runner.testFiles.length} test files...\n`));
88+
this.logger.log(bold(`Running ${this.runner.testFiles.length} test files...\n`));
8989
}
9090

9191
if (this.config.open) {
@@ -316,7 +316,7 @@ export class TestRunnerCli {
316316
if (this.config.watch) {
317317
if (this.runner.focusedTestFile) {
318318
reports.push(
319-
`Focused on test file: ${chalk.cyanBright(
319+
`Focused on test file: ${cyan(
320320
path.relative(process.cwd(), this.runner.focusedTestFile),
321321
)}\n`,
322322
);
@@ -359,9 +359,7 @@ export class TestRunnerCli {
359359
const { message, code, line, column } = error;
360360
const result = codeFrameColumns(code, { start: { line, column } }, { highlightCode: true });
361361
const relativePath = path.relative(process.cwd(), filePath);
362-
report.push(
363-
chalk.red(`Error while transforming ${chalk.cyanBright(relativePath)}: ${message}`),
364-
);
362+
report.push(red(`Error while transforming ${cyan(relativePath)}: ${message}`));
365363
report.push(result);
366364
report.push('');
367365
}

packages/test-runner-core/src/cli/getManualDebugMenu.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import chalk from 'chalk';
1+
import { cyan, gray } from 'nanocolors';
22
import ip from 'ip';
33

44
import { TestRunnerCoreConfig } from '../config/TestRunnerCoreConfig';
@@ -13,10 +13,10 @@ export function getManualDebugMenu(config: TestRunnerCoreConfig): string[] {
1313
"Advanced functionalities such commands for changing viewport and screenshots don't work there.",
1414
'Use the regular debug option to debug in a controlled browser.',
1515
' ',
16-
`Local address: ${chalk.cyanBright(localAddress)}`,
17-
`Network address: ${chalk.cyanBright(networkAddress)}`,
16+
`Local address: ${cyan(localAddress)}`,
17+
`Network address: ${cyan(networkAddress)}`,
1818
' ',
19-
`${chalk.gray('Press')} D ${chalk.gray('to open the browser.')}`,
20-
`${chalk.gray('Press')} ${config.manual ? 'Q' : 'ESC'} ${chalk.gray('to exit manual debug.')}`,
19+
`${gray('Press')} D ${gray('to open the browser.')}`,
20+
`${gray('Press')} ${config.manual ? 'Q' : 'ESC'} ${gray('to exit manual debug.')}`,
2121
].filter(_ => !!_);
2222
}

packages/test-runner-core/src/cli/getSelectFilesMenu.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
1-
import chalk from 'chalk';
1+
import { cyan, red } from 'nanocolors';
22
import { relative } from 'path';
33

44
export function getSelectFilesMenu(succeededFiles: string[], failedFiles: string[]) {
55
const maxI = succeededFiles.length + failedFiles.length;
66
const minWidth = maxI.toString().length + 1;
77

88
function formatTestFile(file: string, i: number, offset: number, failed: boolean) {
9-
return `[${i + offset}]${' '.repeat(
10-
Math.max(0, minWidth - (i + offset).toString().length),
11-
)}${chalk[failed ? 'red' : 'cyan'](relative(process.cwd(), file))}`;
9+
const relativePath = relative(process.cwd(), file);
10+
return `[${i + offset}]${' '.repeat(Math.max(0, minWidth - (i + offset).toString().length))}${
11+
failed ? red(relativePath) : cyan(relativePath)
12+
}`;
1213
}
1314

1415
const entries: string[] = [
Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import chalk from 'chalk';
1+
import { gray } from 'nanocolors';
22

33
export function getWatchCommands(
44
coverage: boolean,
@@ -7,23 +7,21 @@ export function getWatchCommands(
77
): string[] {
88
if (focusedTest) {
99
return [
10-
`${chalk.gray('Press')} F ${chalk.gray('to focus another test file.')}`,
11-
`${chalk.gray('Press')} D ${chalk.gray('to debug in the browser.')}`,
12-
coverage ? `${chalk.gray('Press')} C ${chalk.gray('to view coverage details.')}` : '',
13-
`${chalk.gray('Press')} Q ${chalk.gray('to exit watch mode.')}`,
14-
`${chalk.gray('Press')} Enter ${chalk.gray('to re-run this test file.')}`,
15-
`${chalk.gray('Press')} ESC ${chalk.gray('to exit focus mode')}`,
10+
`${gray('Press')} F ${gray('to focus another test file.')}`,
11+
`${gray('Press')} D ${gray('to debug in the browser.')}`,
12+
coverage ? `${gray('Press')} C ${gray('to view coverage details.')}` : '',
13+
`${gray('Press')} Q ${gray('to exit watch mode.')}`,
14+
`${gray('Press')} Enter ${gray('to re-run this test file.')}`,
15+
`${gray('Press')} ESC ${gray('to exit focus mode')}`,
1616
].filter(_ => !!_);
1717
}
1818

1919
return [
20-
testFiles.length > 1
21-
? `${chalk.gray('Press')} F ${chalk.gray('to focus on a test file.')}`
22-
: '',
23-
`${chalk.gray('Press')} D ${chalk.gray('to debug in the browser.')}`,
24-
`${chalk.gray('Press')} M ${chalk.gray('to debug manually in a custom browser.')}`,
25-
coverage ? `${chalk.gray('Press')} C ${chalk.gray('to view coverage details.')}` : '',
26-
`${chalk.gray('Press')} Q ${chalk.gray('to quit watch mode.')}`,
27-
`${chalk.gray('Press')} Enter ${chalk.gray('to re-run all tests.')}`,
20+
testFiles.length > 1 ? `${gray('Press')} F ${gray('to focus on a test file.')}` : '',
21+
`${gray('Press')} D ${gray('to debug in the browser.')}`,
22+
`${gray('Press')} M ${gray('to debug manually in a custom browser.')}`,
23+
coverage ? `${gray('Press')} C ${gray('to view coverage details.')}` : '',
24+
`${gray('Press')} Q ${gray('to quit watch mode.')}`,
25+
`${gray('Press')} Enter ${gray('to re-run all tests.')}`,
2826
].filter(_ => !!_);
2927
}

packages/test-runner/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,12 +81,12 @@
8181
"@web/test-runner-core": "^0.10.20",
8282
"@web/test-runner-mocha": "^0.7.4",
8383
"camelcase": "^6.2.0",
84-
"chalk": "^4.1.0",
8584
"command-line-args": "^5.1.1",
8685
"command-line-usage": "^6.1.1",
8786
"convert-source-map": "^1.7.0",
8887
"diff": "^5.0.0",
8988
"globby": "^11.0.1",
89+
"nanocolors": "^0.1.6",
9090
"portfinder": "^1.0.28",
9191
"source-map": "^0.7.3"
9292
},

packages/test-runner/src/reporter/getCodeCoverage.ts

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { CoverageThresholdConfig, TestCoverage, CoverageConfig } from '@web/test-runner-core';
22
import path from 'path';
3-
import chalk from 'chalk';
3+
import { bold, green, red, underline } from 'nanocolors';
44

55
const coverageTypes: (keyof CoverageThresholdConfig)[] = [
66
'lines',
@@ -20,28 +20,25 @@ export function getCodeCoverage(
2020
const avgCoverage = Math.round((coverageSum * 100) / 4) / 100;
2121

2222
if (!Number.isNaN(avgCoverage)) {
23-
entries.push(
24-
`Code coverage: ${chalk.bold(
25-
chalk[testCoverage.passed ? 'green' : 'red'](`${avgCoverage} %`),
26-
)}`,
27-
);
23+
const percent = `${avgCoverage} %`;
24+
entries.push(`Code coverage: ${bold(testCoverage.passed ? green(percent) : red(percent))}`);
2825
}
2926

3027
if (!testCoverage.passed && coverageConfig.threshold) {
3128
coverageTypes.forEach(type => {
3229
if (testCoverage.summary[type].pct < coverageConfig.threshold![type]) {
3330
entries.push(
34-
`Coverage for ${chalk.bold(type)} failed with ${chalk.bold(
35-
chalk.red(`${testCoverage.summary[type].pct} %`),
36-
)} compared to configured ${chalk.bold(`${coverageConfig.threshold![type]} %`)}`,
31+
`Coverage for ${bold(type)} failed with ${bold(
32+
red(`${testCoverage.summary[type].pct} %`),
33+
)} compared to configured ${bold(`${coverageConfig.threshold![type]} %`)}`,
3734
);
3835
}
3936
});
4037
}
4138

4239
if (!watch && coverageConfig.report && coverageConfig.reporters?.includes('lcov')) {
4340
entries.push(
44-
`View full coverage report at ${chalk.underline(
41+
`View full coverage report at ${underline(
4542
path.join(coverageConfig.reportDir ?? '', 'lcov-report', 'index.html'),
4643
)}`,
4744
);

0 commit comments

Comments
 (0)