Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace chalk with nanocolors #13783

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 7 additions & 7 deletions Gulpfile.mjs
Expand Up @@ -4,7 +4,7 @@ import { createRequire } from "module";
import { fileURLToPath } from "url";
import plumber from "gulp-plumber";
import through from "through2";
import chalk from "chalk";
import { green, cyan, yellow } from "nanocolors";
import fancyLog from "fancy-log";
import filter from "gulp-filter";
import gulp from "gulp";
Expand Down Expand Up @@ -107,7 +107,7 @@ function generateHelpers(generator, dest, filename, message) {
file.contents = Buffer.from(
formatCode(await generateCode(filename), dest + file.path)
);
fancyLog(`${chalk.green("✔")} Generated ${message}`);
fancyLog(`${green("✔")} Generated ${message}`);
callback(null, file);
})
)
Expand Down Expand Up @@ -291,7 +291,7 @@ function buildRollup(packages, targetBrowsers) {
);

const input = getIndexFromPackage(src);
fancyLog(`Compiling '${chalk.cyan(input)}' with rollup ...`);
fancyLog(`Compiling '${cyan(input)}' with rollup ...`);
const bundle = await rollup({
input,
external,
Expand Down Expand Up @@ -396,15 +396,15 @@ function buildRollup(packages, targetBrowsers) {

if (!process.env.IS_PUBLISH) {
fancyLog(
chalk.yellow(
`Skipped minification of '${chalk.cyan(
yellow(
`Skipped minification of '${cyan(
outputFile
)}' because not publishing`
)
);
return undefined;
}
fancyLog(`Minifying '${chalk.cyan(outputFile)}'...`);
fancyLog(`Minifying '${cyan(outputFile)}'...`);

await bundle.write({
file: outputFile.replace(/\.js$/, ".min.js"),
Expand Down Expand Up @@ -432,7 +432,7 @@ function buildRollupDts(packages) {
packages.map(async packageName => {
const input = `${mapToDts(packageName)}/src/index.d.ts`;
const output = `${packageName}/lib/index.d.ts`;
fancyLog(`Bundling '${chalk.cyan(output)}' with rollup ...`);
fancyLog(`Bundling '${cyan(output)}' with rollup ...`);

const bundle = await rollup({
input,
Expand Down
4 changes: 2 additions & 2 deletions babel-worker.cjs
@@ -1,7 +1,7 @@
const { transformSync } = require("@babel/core");
const { mkdirSync, statSync, readFileSync, writeFileSync } = require("fs");
const { dirname } = require("path");
const chalk = require("chalk");
const { cyan } = require("nanocolors");
const fancyLog = require("fancy-log");

function needCompile(src, dest) {
Expand All @@ -24,7 +24,7 @@ exports.transform = function (src, dest) {
if (!needCompile(src, dest)) {
return;
}
fancyLog(`Compiling '${chalk.cyan(src)}'...`);
fancyLog(`Compiling '${cyan(src)}'...`);
const content = readFileSync(src, { encoding: "utf8" });
const { code } = transformSync(content, {
filename: src,
Expand Down
4 changes: 2 additions & 2 deletions lib/babel-packages.js.flow
Expand Up @@ -180,7 +180,7 @@ declare module "@babel/generator" {
}

declare module "@babel/highlight" {
import typeof { Chalk } from "chalk";
import typeof { Colors } from "nanocolors";
declare type Options = {
forceColor?: boolean,
};
Expand All @@ -193,7 +193,7 @@ declare module "@babel/highlight" {
/**
* The Chalk instance that should be used given the passed options.
*/
declare function getChalk(options: Options): Chalk;
declare function getChalk(options: Options): Colors;

/**
* Highlight `code`.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -43,7 +43,6 @@
"@typescript-eslint/eslint-plugin": "^4.18.0",
"@typescript-eslint/parser": "^4.18.0",
"babel-plugin-transform-charcodes": "^0.2.0",
"chalk": "^2.4.2",
"charcodes": "^0.2.0",
"enhanced-resolve": "^5.8.2",
"eslint": "^7.27.0",
Expand All @@ -64,6 +63,7 @@
"lint-staged": "^9.2.0",
"lodash": "^4.17.21",
"mergeiterator": "^1.2.5",
"nanocolors": "^0.2.3",
"prettier": "2.3.1",
"rollup": "~2.54.0",
"rollup-plugin-dts": "^2.0.0",
Expand Down
3 changes: 1 addition & 2 deletions packages/babel-code-frame/package.json
Expand Up @@ -19,8 +19,7 @@
"@babel/highlight": "workspace:^7.14.5"
},
"devDependencies": {
"@types/chalk": "^2.0.0",
"chalk": "^2.0.0",
"nanocolors": "^0.2.3",
"strip-ansi": "^4.0.0"
},
"engines": {
Expand Down
23 changes: 13 additions & 10 deletions packages/babel-code-frame/src/index.ts
Expand Up @@ -35,13 +35,16 @@ export interface Options {
}

/**
* Chalk styles for code frame token types.
* Nano Colors styles for code frame token types.
*/
function getDefs(chalk) {
function getDefs(colors) {
function redBold(s) {
return colors.red(colors.bold(s));
}
return {
gutter: chalk.grey,
marker: chalk.red.bold,
message: chalk.red.bold,
gutter: colors.gray,
marker: redBold,
message: redBold,
};
}

Expand Down Expand Up @@ -133,10 +136,10 @@ export function codeFrameColumns(
): string {
const highlighted =
(opts.highlightCode || opts.forceColor) && shouldHighlight(opts);
const chalk = getChalk(opts);
const defs = getDefs(chalk);
const maybeHighlight = (chalkFn, string) => {
return highlighted ? chalkFn(string) : string;
const colors = getChalk(opts);
const defs = getDefs(colors);
const maybeHighlight = (color, string) => {
return highlighted ? color(string) : string;
};
const lines = rawLines.split(NEWLINE);
const { start, end, markerLines } = getMarkerLines(loc, lines, opts);
Expand Down Expand Up @@ -194,7 +197,7 @@ export function codeFrameColumns(
}

if (highlighted) {
return chalk.reset(frame);
return colors.reset(frame);
} else {
return frame;
}
Expand Down
14 changes: 6 additions & 8 deletions packages/babel-code-frame/test/index.js
@@ -1,4 +1,4 @@
import chalk from "chalk";
import { red, bold, gray, yellow, reset } from "nanocolors";
import stripAnsi from "strip-ansi";
import codeFrame, { codeFrameColumns } from "..";

Expand Down Expand Up @@ -262,8 +262,7 @@ describe("@babel/code-frame", function () {
});

test("opts.forceColor", function () {
const marker = chalk.red.bold;
const gutter = chalk.grey;
const gutter = gray;

const rawLines = ["", "", "", ""].join("\n");
expect(
Expand All @@ -273,19 +272,18 @@ describe("@babel/code-frame", function () {
forceColor: true,
}),
).toEqual(
chalk.reset(
reset(
[
" " + gutter(" 2 |"),
marker(">") + gutter(" 3 |"),
red(bold(">")) + gutter(" 3 |"),
" " + gutter(" 4 |"),
].join("\n"),
),
);
});

test("jsx", function () {
const gutter = chalk.grey;
const yellow = chalk.yellow;
const gutter = gray;

const rawLines = ["<div />"].join("\n");

Expand All @@ -299,7 +297,7 @@ describe("@babel/code-frame", function () {
),
).toEqual(
JSON.stringify(
chalk.reset(
reset(
" " +
gutter(" 1 |") +
" " +
Expand Down
5 changes: 2 additions & 3 deletions packages/babel-highlight/package.json
Expand Up @@ -16,11 +16,10 @@
"main": "./lib/index.js",
"dependencies": {
"@babel/helper-validator-identifier": "workspace:^7.14.5",
"chalk": "^2.0.0",
"js-tokens": "condition:BABEL_8_BREAKING ? ^7.0.0 : ^4.0.0"
"js-tokens": "condition:BABEL_8_BREAKING ? ^7.0.0 : ^4.0.0",
"nanocolors": "^0.2.3"
},
"devDependencies": {
"@types/chalk": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"engines": {
Expand Down
41 changes: 19 additions & 22 deletions packages/babel-highlight/src/index.ts
@@ -1,15 +1,14 @@
/// <reference path="../../../lib/third-party-libs.d.ts" />

import type { Token, JSXToken } from "js-tokens";
import type { Colors, Color } from "nanocolors";
import jsTokens from "js-tokens";

import {
isStrictReservedWord,
isKeyword,
} from "@babel/helper-validator-identifier";
import Chalk from "chalk";

type ChalkClass = ReturnType<typeof getChalk>;
import { isColorSupported, createColors } from "nanocolors";

/**
* Names that are always allowed as identifiers, but also appear as keywords
Expand All @@ -34,19 +33,19 @@ type InternalTokenType =
| "invalid";

/**
* Chalk styles for token types.
* Nano Colors styles for token types.
*/
function getDefs(chalk: ChalkClass): Record<InternalTokenType, ChalkClass> {
function getDefs(colors: Colors): Record<InternalTokenType, Color> {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsxIdentifier: chalk.yellow,
punctuator: chalk.yellow,
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
keyword: colors.cyan,
capitalized: colors.yellow,
jsxIdentifier: colors.yellow,
punctuator: colors.yellow,
number: colors.magenta,
string: colors.green,
regex: colors.magenta,
comment: colors.gray,
invalid: s => colors.white(colors.bgRed(colors.bold(s))),
};
}

Expand Down Expand Up @@ -216,7 +215,7 @@ if (process.env.BABEL_8_BREAKING) {
/**
* Highlight `text` using the token definitions in `defs`.
*/
function highlightTokens(defs: Record<string, ChalkClass>, text: string) {
function highlightTokens(defs: Record<string, Color>, text: string) {
let highlighted = "";

for (const { type, value } of tokenize(text)) {
Expand Down Expand Up @@ -246,25 +245,23 @@ type Options = {
* Whether the code should be highlighted given the passed options.
*/
export function shouldHighlight(options: Options): boolean {
return !!Chalk.supportsColor || options.forceColor;
return isColorSupported || options.forceColor;
}

/**
* The Chalk instance that should be used given the passed options.
* The Nano Colors instance that should be used given the passed options.
*/
export function getChalk(options: Options) {
return options.forceColor
? new Chalk.constructor({ enabled: true, level: 1 })
: Chalk;
return createColors(options.forceColor);
}

/**
* Highlight `code`.
*/
export default function highlight(code: string, options: Options = {}): string {
if (shouldHighlight(options)) {
const chalk = getChalk(options);
const defs = getDefs(chalk);
const colors = getChalk(options);
const defs = getDefs(colors);
return highlightTokens(defs, code);
} else {
return code;
Expand Down
2 changes: 2 additions & 0 deletions packages/babel-highlight/test/helpers/disable-colors.js
@@ -0,0 +1,2 @@
process.env.NO_COLOR = 1;
delete process.env.FORCE_COLOR;
2 changes: 2 additions & 0 deletions packages/babel-highlight/test/helpers/enable-colors.js
@@ -0,0 +1,2 @@
delete process.env.NO_COLOR;
process.env.FORCE_COLOR = 1;
40 changes: 40 additions & 0 deletions packages/babel-highlight/test/index.color.js
@@ -0,0 +1,40 @@
import "./helpers/enable-colors";
import { createColors } from "nanocolors";
import stripAnsi from "strip-ansi";
import highlight, { shouldHighlight, getChalk } from "../lib";

describe("@babel/highlight when colors are supported", function () {
describe("highlight", function () {
it("highlights code", function () {
const code = "console.log('hi')";
const result = highlight(code);
const stripped = stripAnsi(result);
expect(result.length).toBeGreaterThan(stripped.length);
expect(stripped).toBe(code);
});
});

describe("shouldHighlight", function () {
it("returns true", function () {
expect(shouldHighlight({})).toBeTruthy();
});
});
});

describe("getChalk", function () {
describe("when forceColor is not passed", function () {
it("returns a Chalk instance", function () {
expect(Object.keys(getChalk({})).sort()).toEqual(
Object.keys(createColors()).sort(),
);
});
});

describe("when forceColor is passed", function () {
it("returns a Chalk instance", function () {
expect(Object.keys(getChalk({ forceColor: true })).sort()).toEqual(
Object.keys(createColors()).sort(),
);
});
});
});