Generate declaration file with single module in TypeScript
Asked Answered
P

2

15

Given the following folder structure:

src/
├── foo.ts
├── bar.ts
├── baz.ts
├── index.ts

Where foo.ts, bar.ts, and baz.ts each export a default class or thing: i.e. in the case of foo.ts:

export default class Foo {
    x = 2;
}

Can we automatically generate a declaration file which declares one module my-module and exports foo.ts, bar.ts, and baz.ts as non-defaults?

I.e. I want tsc to generate the following:

build/
├── foo.js
├── bar.js
├── baz.js
├── index.js
├── index.d.ts

Where index.d.ts contains:

declare module 'my-module' {
    export class Foo {
        ...
    }
    export class Bar {
        ...
    }
    export class Baz {
        ...
    }
}

I see that mostly all NPM modules have a declaration file like this and maybe with separate files.

How would I accomplish this?

Phenylamine answered 30/10, 2018 at 8:13 Comment(1)
This TypeScript issue is for generating a "flattened" declaration file and has links to some third-party tools that you could try. May I ask why you want this? Generating a .d.ts file per .js file will work fine for being able to find type information, though a flattened .d.ts file may be easier for users to understand and may make it easier to hide elements that you don't consider public API.Otherdirected
M
-1

In your tsconfig.json file, set "declaration" to true. Then when you run typescript on your project it will automatically generate declaration files for you.

Midsummer answered 20/7, 2019 at 22:55 Comment(1)
Johan is asking how to bundle all type declaration files in one instead of emitting the type declaration file.Autoerotic
D
-1

tsup

It can do that and is pretty fast (1.5s):

tsup ./executors/index.ts --dts-only

You need to import the types in ./executors/index.ts and export them from this file.

dts-bundle-generator

It was slower for me (8.5s):

dts-bundle-generator --out-file dist/testkube-executors.d.ts ./executors/executors.ts
Deathlike answered 27/10, 2023 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.