【问题标题】:Importing Node.js SDK into Typescript running in Node server gave error "ReferenceError: require is not defined"将 Node.js SDK 导入在 Node 服务器中运行的 Typescript 中出现错误“ReferenceError:未定义要求”
【发布时间】:2021-06-04 13:42:43
【问题描述】:

我正在开发用于服务器端的 Node.js SDK,并在尝试使用 Typescript 将其导入我的 express 应用程序时遇到此问题“ReferenceError: require is not defined”。最初我没有生成 .d.ts 文件,所以我导入了 Typescript 并生成了声明文件,但仍然出现错误。我在 SDK 包中的 index.js:

const myDep = require('./myDep');
const client = function (sdkKey) {
    const c = {};
    c.do = (user) => {};
    return c;
}

module.exports = client;

生成的 index.d.ts 文件如下所示:

export = client;
declare function client(sdkKey: any): {
    do(user: any): void;
};

这是我的 SDK 包中的 tsconfig.json:

{
  "include": ["src/**/*", "src/index.d.ts"],
  "compilerOptions": {
    "resolveJsonModule": true,
    "target": "es6",
    "lib": ["es6"],
    "module": "commonjs",
    "allowJs": true,
    "checkJs": true,
    "declaration": true,
    "emitDeclarationOnly": true,
    "moduleResolution": "Node",
    "outDir": "./dist"
  }
}

我正在使用 npm 链接将其导入运行 typescript 的节点服务器中,并在我的 app.ts 文件中使用导入

import * as mySDK from 'my-node-js-sdk';

【问题讨论】:

    标签: javascript node.js typescript npm


    【解决方案1】:

    最终解决了这个问题,并通过添加一个 index.d.ts 文件进行类型声明来修复它。在我的项目中还发现了几个地方,我使用的是 ES6 导出而不是模块,所以也必须修复这些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-20
      • 2018-03-01
      • 1970-01-01
      • 2017-08-19
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多