导入映射
【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!.】