导入映射
¥Import maps
前面的两个示例定义了 load
钩子。这是 resolve
钩子的示例。这个钩子模块读取一个 import-map.json
文件,该文件定义了要覆盖其他 URL 的说明符(这是 "导入映射" 规范的一小部分的非常简单的实现)。
¥The previous two examples defined load
hooks. This is an example of a
resolve
hook. This hooks module reads an import-map.json
file that defines
which specifiers to override to other URLs (this is a very simplistic
implementation of a small subset of the "import maps" specification).
// import-map-hooks.js
import fs from 'node:fs/promises';
const { imports } = JSON.parse(await fs.readFile('import-map.json'));
export async function resolve(specifier, context, nextResolve) {
if (Object.hasOwn(imports, specifier)) {
return nextResolve(imports[specifier], context);
}
return nextResolve(specifier, context);
}
有了这些文件:
¥With these files:
// main.js
import 'a-module';
// import-map.json
{
"imports": {
"a-module": "./some-module.js"
}
}
// some-module.js
console.log('some module!');
运行 node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js
应打印 some module!
。
¥Running node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js
should print some module!
.