On this page

🌐 Chalk to util.styleText()

chalk npm 包的使用迁移到 Node.js 内置的 util.styleText() API。用 { styleText }node:util 替换 chalk 的导入,并相应地重写所有 chalk 方法调用。链式 chalk 样式会被转换为样式字符串数组。

🌐 Migrates usage of the chalk npm package to the Node.js built-in util.styleText() API. Replaces the chalk import with { styleText } from node:util and rewrites all chalk method calls accordingly. Chained chalk styles are converted to an array of style strings.

🌐 Usage

使用这个 codemod 运行:

🌐 Run this codemod with:

🌐 Examples

🌐 Example 1

基本颜色方法(ESM 默认导入)

🌐 Basic color methods (ESM default import)

-import chalk from "chalk";
+import { styleText } from "node:util";

-console.log(chalk.red("Error message"));
-console.log(chalk.green("Success message"));
-console.log(chalk.blue("Info message"));
+console.log(styleText("red", "Error message"));
+console.log(styleText("green", "Success message"));
+console.log(styleText("blue", "Info message"));

🌐 Example 2

链式风格

🌐 Chained styles

-import chalk from "chalk";
+import { styleText } from "node:util";

-console.log(chalk.red.bold("Error: Operation failed"));
-console.log(chalk.green.underline("Success: All tests passed"));
-console.log(chalk.yellow.bgBlack("Warning: Deprecated API usage"));
+console.log(styleText(["red", "bold"], "Error: Operation failed"));
+console.log(styleText(["green", "underline"], "Success: All tests passed"));
+console.log(styleText(["yellow", "bgBlack"], "Warning: Deprecated API usage"));

🌐 Example 3

CommonJS require

-const chalk = require("chalk");
+const { styleText } = require("node:util");

-const error = chalk.red("Error");
-const warning = chalk.yellow("Warning");
-const info = chalk.blue("Info");
+const error = styleText("red", "Error");
+const warning = styleText("yellow", "Warning");
+const info = styleText("blue", "Info");

 console.log(error, warning, info);

🌐 Notes

🌐 Limitations

没有直接 util.styleText 对应的方法——包括 hex()rgb()ansi256()bgAnsi256()visible()new chalk.Chalk() ——会被跳过。每次不支持的调用都会打印警告,这些调用点会保持不变,以便手动检查。

🌐 Chalk methods that have no direct util.styleText equivalent — including hex(), rgb(), ansi256(), bgAnsi256(), visible(), and new chalk.Chalk() — are skipped. A warning is printed for each unsupported call, and those call sites are left unchanged for manual review.