网站搜索

从 TypeScript 使用 JavaScript 库(带有继承的 JavaScript 依赖)


上下文

我正在用纯 TypeScript 构建一个项目,以与聊天服务器通信。为了进行这种通信,我使用了 strophe.js 库。

Strophe 库有三种版本:commonjs、esm 和 umd。根据我搜索到的内容,我并不完全理解这些格式之间的区别:

  • commonjs 是用于 Node 的
  • esm 用于网络应用
  • umd 是通用的

基于此,我可以使用esm或umd,因为这个应用程序打算在浏览器中运行。

我写了一个 Typescript 文件作为 strophe 库的封装。这是我如何导入它的:

import * as core from './dependencies/strophe.umd.js'; // using UMD
import core from './dependencies/strophe.esm.js'; // using ESM
const Strophe = core.Strophe;

// ...
// Usage example:
this.conn = new Strophe.Connection(options.connection, options.options);

我的问题

使用 ESM 格式时:

我可以看到接口定义,调用它的函数,等等。一切都很好,但浏览器抛出:Uncaught TypeError: 无法解析模块说明符 "abab"。相对引用必须以 "/"、"./" 或 "../" 开头。

使用 UMD 格式时:

起初没有显示错误,但 Strophe 没有被正确导入。尝试调用 connect 函数时,会抛出此错误:

Uncaught TypeError: Cannot read property 'Connection' of undefined

更新


沙盒:https://codesandbox.io/s/bitter-grass-sh4s9

为了测试这个,我运行 tsc,然后运行 live-server 来提供文件

tsconfig.json

{
  "extends": "@tsconfig/recommended/tsconfig.json",
  "compilerOptions": {
    "target": "es2015",
    "module": "es2015",
    "baseUrl": "src",
    "outDir": "build",
    "sourceMap": false,
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "allowJs": true,
    "noImplicitAny": false,
    "moduleResolution": "node",
    "removeComments": true,
    "lib": ["es2018", "dom"],
    "types": ["jest", "node"],
    "paths": {
      "@core/*": ["./src/core"]
    }
  },
  "include": ["src/**/*.ts"]
}

答案#1

通过像 npm 或 Yarn 这样的包管理器将 Strophe.js 添加为依赖项是个好主意。看起来你是手动将它们放在名为 dependencies 的文件夹中。

添加依赖项:yarn add strophe.js
添加类型声明:yarn add -D @types/strophe.js

这将把 Strophe.js 下载到你的 node_modules 文件夹中。

在你的代码中导入它:

import { Strophe } from "strophe.js";
this.conn = new Strophe.Connection(options.connection, options.options);

相关文章