该手册在以下三个部分中介绍了这种情况:
我将展示一个可重现的示例,而不是复制 + 粘贴文档中的所有内容(因为一些复制的 sn-ps 还不够;这是一个多方面的问题)——但是请注意导入映射中的值,因为它们是通过阅读文档的所有三个链接部分得出的:
./import_map.json:
{
"imports": {
"chalk": "npm:chalk@5.2.0",
"node:util": "https://deno.land/std@0.170.0/node/util.ts"
}
}
./deno.jsonc:
{
"importMap": "./import_map.json",
"tasks": {
// I included these permissions (which are required by chalk) in advance to avoid needing to grant them one-by-one at runtime:
"dev": "deno run --allow-env=FORCE_COLOR,TF_BUILD,TERM,CI,TEAMCITY_VERSION,COLORTERM,TERM_PROGRAM,TERM_PROGRAM_VERSION src/linked-queue.ts"
}
}
./src/linked-queue.ts:
import * as util from "node:util";
import chalk from "chalk";
console.log('util:', typeof util); // util: object
console.log('chalk:', typeof chalk); // chalk: function
使用定义的任务在终端中运行:
% deno --version
deno 1.29.1 (release, x86_64-apple-darwin)
v8 10.9.194.5
typescript 4.9.4
% deno task dev
Task dev deno run --allow-env=FORCE_COLOR,TF_BUILD,TERM,CI,TEAMCITY_VERSION,COLORTERM,TERM_PROGRAM,TERM_PROGRAM_VERSION src/linked-queue.ts
util: object
chalk: function
% echo $?
0
到目前为止,Deno 的一切都很好。
让我们检查一下相同的代码在 Node.js 中是否可以不加修改地工作。需要添加以下文件才能使用 Node 进行编译和运行,因为它不包含 Deno 的所有内置工具:
./package.json:
{
"name": "so-74905332",
"version": "0.1.0",
"type": "module",
"scripts": {
"compile": "tsc",
"dev": "tsc && node src/linked-queue.js"
},
"license": "MIT",
"dependencies": {
"chalk": "5.2.0"
},
"devDependencies": {
"@types/node": "^18.11.17",
"typescript": "^4.9.4"
}
}
./tsconfig.json:
为什么有这些值?我只是使用 recommended base,链接到 TS repo wiki:
// This file was autogenerated by a script
// Equivalent to a config of: strictest extends esm extends node18
{
"$schema": "https://json.schemastore.org/tsconfig",
"display": "Node LTS + ESM + Strictest",
"_version": "18.12.1",
"compilerOptions": {
"lib": [
"es2022"
],
"module": "es2022",
"target": "es2022",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"allowUnusedLabels": false,
"allowUnreachableCode": false,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"importsNotUsedAsValues": "error",
"checkJs": true
}
}
使用定义的 npm 脚本在终端中运行:
% node --version
v18.12.1
% npm install
added 3 packages, and audited 4 packages in 1s
1 package is looking for funding
run `npm fund` for details
found 0 vulnerabilities
% npm run dev
> so-74905332@0.1.0 dev
> tsc && node src/linked-queue.js
util: object
chalk: function
% echo $?
0
相同的模块源代码也适用于 Node.js。