【问题标题】:ESM import a .node addonESM 导入 .node 插件
【发布时间】:2022-12-04 07:18:57
【问题描述】:

我正在尝试在基于 ESM 和 Node Typescript 的上下文中导入 .node 二进制插件。但是,当我尝试这样做时,出现以下错误“错误 TS2307:找不到模块‘./addon.node’或其相应的类型声明。”

我在网上寻找了几种解决方案,这些是我的版本: 节点JS:v16.14.1 ts节点:v10.7.0 打字稿:4.6.3

这是我目前的导入方法:

import addon from "./addon.node";

请注意,由于我的配置,我仅限于使用导入。 在此先感谢您的支持。

【问题讨论】:

  • 该帖子中的答案并不是很直接。
  • 这应该是朝着正确方向迈出的一步,因为您遇到的错误与无法导入文件无关,这是因为节点附加组件中没有类型。按照说明进行操作,如果失败,请更新您的问题并报告。

标签: node.js typescript


【解决方案1】:

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);
}

【讨论】:

    猜你喜欢
    • 2020-11-14
    • 2022-12-07
    • 1970-01-01
    • 2021-01-16
    • 2021-11-23
    • 2022-01-20
    • 2019-11-19
    • 2023-01-31
    • 2021-12-24
    相关资源
    最近更新 更多