【发布时间】:2021-04-23 01:50:58
【问题描述】:
前面已经问过如何生成带有类型定义的库的问题了:
Generate declaration file with single module in TypeScript
答案说你只需要在 tsconfig.json 中将“声明”设置为 true。
我在这个 github 存储库中整理了一个简单的 example_library 和 example_library_consumer 项目:
https://github.com/jmc420/typescript_examples https://github.com/jmc420/typescript_examples/tree/master/example_library https://github.com/jmc420/typescript_examples/tree/master/example_library_consumer
在 example_library 中,我创建了一个 index.ts,用于导出我要导出的类和接口:
export * from './ILogin';
export * from './Login';
typescript 编译器生成一个与此相同的 index.d.ts,并且不包含模块声明。
我使用此依赖项在 package.json 中的 example_library_consumer 中导入库:
"examplelibrary": "file:../example_library"
src/ts/index.ts 使用这个库:
import {ILogin, Login} from 'examplelibrary';
let login:ILogin = new Login("somebody@nobody.com", "password");
console.log("Email "+login.getPassword());
一切编译正常,tsc 编译生成:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var examplelibrary_1 = require("examplelibrary");
var login = new examplelibrary_1.Login("somebody@nobody.com", "password");
console.log("Email " + login.getPassword());
当我运行它时,我得到一个运行时错误:
var login = new examplelibrary_1.Login("somebody@nobody.com", "password");
^
TypeError: examplelibrary_1.Login is not a constructor
大多数库的 index.d.ts 使用“声明模块”并怀疑这是问题所在。声明标志设置为true的tsc编译器能否生成“声明模块”?
【问题讨论】:
标签: typescript typescript-typings tsc