【问题标题】:Generate declaration file with single module in TypeScript not working在 TypeScript 中使用单个模块生成声明文件不起作用
【发布时间】: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


    【解决方案1】:

    问题出在导出上:

    export * from './ILogin';
    export * from './Login';
    

    通过将导出更改为以下内容解决了问题:

    export {ILogin} from './ILogin';
    export {Login} from './Login';
    

    导出默认类或接口必须更改为导出类或导出接口。您不能导出默认类。 Typescript 编译器(3.9.6 版)不喜欢这样:

    export ILogin from './ILogin';
    export Login from './Login';
    

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 2015-11-22
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      相关资源
      最近更新 更多