简体   繁体   English

为捆绑的 javascript 库导入 typescript 定义

[英]Importing typescript definitions for my bundled javascript library

I have a library I wrote in typescript, it contains multiple files and an index.ts file that contains all the exports of the library.我有一个我在 typescript 中编写的库,它包含多个文件和一个 index.ts 文件,其中包含库的所有导出。

I used webpack to compile the entire library into a single index.js file but I'm having trouble importing it WITH type definitions.我使用 webpack 将整个库编译为单个 index.js 文件,但我无法使用类型定义导入它。

Lets say this is my library:可以说这是我的图书馆:

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

So I copied the output folder to my other project but when I try to create a class that inherits one of my library's classes I get an error:所以我将 output 文件夹复制到我的另一个项目中,但是当我尝试创建一个继承我的库的一个类的 class 时,我收到一个错误:

// 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

I know I can work around this by using require() but I'd prefer having the actual typings in my other projects.我知道我可以通过使用 require() 来解决这个问题,但我更喜欢在我的其他项目中使用实际类型。

The reason I'm doing this is because I'm obfuscating the index.js file but I don't mind exposing the name of the functions it contains.我这样做的原因是因为我混淆了 index.js 文件,但我不介意公开它包含的函数的名称。 It may sound counter-productive but it provides enough security for my needs.这听起来可能适得其反,但它为我的需求提供了足够的安全性。

Is there a way to make typescript detect the d.ts files?有没有办法让 typescript 检测到 d.ts 文件? (or any other way to have obfuscated code with typings) (或任何其他方式使代码与打字混淆)

Just add a "types" declaration to your package.json .只需package.json中添加"types"声明即可

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM