在 Deno 中,Chalk 不会 运行

Chalk won't run in Deno

以下代码来自 Deno Chalk 库的 README。 Deno/Typescript不会让它过去:

import chalk from "https://deno.land/x/chalk_deno@v4.1.1-deno/source/index.js";
// Run this in debugger and it's fine but it won't compile:
console.log(chalk.blue("Hello world!"));
console.log(eval("typeof chalk.blue"), "At runtime it's fine!");

输出:

error: TS2339 [ERROR]: Property 'blue' does not exist on type '{ (...arguments_: any[]): string; Chalk: typeof Chalk; }'. console.log(chalk.blue("Hello world!"));

已修补:

注释掉第 3 行,它运行良好!所以 chalk.blue 在运行时可用但对编译器不可见??

function At runtime it's fine!

第三方代码具有质量参差不齐的类型库是很常见的。

您要导入的特定模块是一个 JavaScript 文件(不包含类型信息)。但是,在 https://deno.land/x/chalk_deno@v4.1.1-deno/index.d.ts.

处有一个类型声明文件。

Deno 有一种针对此类情况的机制,它允许您为要导入的模块提供编译器提示:@deno-types 指令。在这里阅读:https://deno.land/manual@v1.14.3/typescript/types#providing-types-when-importing

您可以在您的案例中这样使用它,在导入语句之前:

// @deno-types="https://deno.land/x/chalk_deno@v4.1.1-deno/index.d.ts"
import chalk from "https://deno.land/x/chalk_deno@v4.1.1-deno/source/index.js";

A bit of context: At present, you'll find quite a few modules at deno.land/x which are simply copied directly from npm packages. Lots of these don't include types, and many still are not even in proper ESM format (using bare specifiers without import maps, etc.), making them completely incompatible with Deno. This variable quality is just the nature of using third-party software (no matter which ecosystem), and unfortunate for you as a consumer, because it increases your work of auditing your dependencies.

我们知道 chalk 是 node 原生的(因为它主要是为 nodejs 构建的)并且它在 deno 上的移植会有一些错误和缺点,因为它们作为它们的父包并不成熟,更不用说 deno 本身了非常新,需要时间才能拥有强大的开发人员友好环境。

但在您的情况下,chalk 模块可以很容易地替换为名为 colors 的 deno 内置模块。 Link :- https://deno.land/std@0.123.0/fmt/colors.ts

The link is in the format of https://deno.land/std@version/fmt/colors.ts where version should be replaced by version you want to use, at the time of writing the latest version is 0.123.0

用法:

// importing colors library from denoland

import {red,blue,bold} from "https://deno.land/std@0.123.0/fmt/colors.ts"

console.log(red("This text will be printed in red");
console.log(blue("This text will be printed in blue");

// merging two properties

console.log(bold(red("This text will be red and bold"));

如您所见,用法与 chalk 模块非常相似,对于完整的 API 文档,您可以查看 denolandhere 上提供的自述文件