Node.js import 不支持 .node 文件。要在 ESM 上下文中导入此类文件,您需要使用 createRequire:
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const addon = require('./addon.node');
您还可以在 ESM 文件随后导入的 CommonJS 文件中导入 .node 文件。
// addon.cjs
module.exports = require('./addon.node');
// main.js
import addon from './addon.cjs';
最后,您可以创建一个 ESM loader,将对 .node 文件的支持添加到 import,方法是将 createRequire 方法包装到加载程序中(未经测试):
import { cwd } from 'node:process';
import { pathToFileURL } from 'node:url';
const baseURL = pathToFileURL(`${cwd()}/`).href;
export async function resolve(specifier, context, nextResolve) {
if (specifier.endsWith('.node')) {
const { parentURL = baseURL } = context;
// Node.js normally errors on unknown file extensions, so return a URL for
// specifiers ending in `.node`.
return {
shortCircuit: true,
url: new URL(specifier, parentURL).href,
};
}
// Let Node.js handle all other specifiers.
return nextResolve(specifier);
}
export async function load(url, context, nextLoad) {
if (url.endsWith('.node')) {
const source = `
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const path = fileURLToPath(${url});
export default require(path);`;
return {
format: 'module',
shortCircuit: true,
source,
};
}
// Let Node.js handle all other URLs.
return nextLoad(url);
}