0
votes

The question of how to generate a library with type definitions has been asked before here:

Generate declaration file with single module in TypeScript

The answers says that you just need to set "declaration" to true in tsconfig.json.

I have put together a simple example_library and example_library_consumer projects in this github repo:

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

In example_library I have created an index.ts that exports the class and interface that I want to export:

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

The typescript compiler generates an index.d.ts that is identical to this and doesn't include a module declaration.

I import the library in example_library_consumer in package.json using this dependency:

"examplelibrary": "file:../example_library"

src/ts/index.ts uses the library thus:

import {ILogin, Login} from 'examplelibrary';

let login:ILogin = new Login("[email protected]", "password");

console.log("Email "+login.getPassword());

Everything compiles ok and the tsc compile generates this:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var examplelibrary_1 = require("examplelibrary");
var login = new examplelibrary_1.Login("[email protected]", "password");
console.log("Email " + login.getPassword());

When I run this, I get a runtime error:

var login = new examplelibrary_1.Login("[email protected]", "password");
            ^
TypeError: examplelibrary_1.Login is not a constructor

Most index.d.ts for libraries use the "declare module" and suspect this is the problem. Can the tsc compiler with the declaration flag set to true generate "declare module"?

1

1 Answers

0
votes

The problem was with the export:

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

The problem was fixed by changing the export to this:

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

The export default class or interface had to be changed to export class or export interface. You can't export a default class. The Typescript compiler (version 3.9.6) doesn't like this:

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