【问题标题】:Importing typescript definitions for my bundled javascript library为我的捆绑 javascript 库导入打字稿定义
【发布时间】:2021-06-17 05:42:37
【问题描述】:

我有一个用 typescript 编写的库,它包含多个文件和一个 index.ts 文件,其中包含该库的所有导出。

我使用 webpack 将整个库编译成单个 index.js 文件,但我无法使用类型定义导入它。

假设这是我的图书馆:

src
-- index.ts
-- items-dal.ts
-- items-bl.ts
output
-- index.js
-- index.d.ts
-- items-dal.d.ts
-- items-bl.d.ts
webpack.config
ts.config
package.json

所以我将输出文件夹复制到我的另一个项目,但是当我尝试创建一个继承我的库类之一的类时,我收到错误:

// user-dal.ts
const { ItemsDAL } = require("./output");

class UsersDAL extends ItemsDAL {
  constructor() {
    super("users");
  }
}

export default new UsersDAL();

// usage
import usersDal from "./users-dal.ts";
usersDal.getAll() // <-- Property "getAll" doesn't exist on type usersDal

我知道我可以通过使用 require() 来解决这个问题,但我更喜欢在我的其他项目中使用实际类型。

我这样做的原因是因为我混淆了 index.js 文件,但我不介意公开它包含的函数的名称。这听起来可能适得其反,但它为我的需求提供了足够的安全性。

有没有办法让 typescript 检测 d.ts 文件? (或任何其他方式使代码与打字混淆)

【问题讨论】:

    标签: node.js typescript webpack typescript-typings


    【解决方案1】:

    只需添加"types" declaration to your package.json。

    {
      ...
      "main": "./output/index.js",
      "types": "./output/index.d.ts",
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 2016-06-17
      • 2018-04-26
      • 2013-08-11
      相关资源
      最近更新 更多