Typescript: Create declarations for UMD module which is written in TS

Viewed 512

I wrote a little library in TS for learning purpose. I am using webpack to create a JS UMD module from my typescript.

My project structure looks like this:

|-dist
    |-js
        |-my-lib.min.js    // Minified library as UMD module
|-src
    |-ts
        |-types
        |-interfaces
        |-utils
        |-components
            |-button.ts
            |-textField.ts
            |-dropdownMenu.ts
        |-my-lib.ts    // Source file for UMD lib

my-lib.ts file:

import {Button} from './components/button';
import {TextField} from './components/textField';
import {DropdownMenu} from './components/dropdownMenu';

export {
    Button,
    TextField,
    DropdownMenu,
}

So when including my-lib.min.js via src in HTML, I can use my components, for instance: (The UMD module is named with webpack in myLib).

const username = new myLib.TextField();

Now I want to use my lib in a new ts project. I do not want that the TS files are delivered but the declarations only. So that I can use my ts lib like it would be a JS UMD module, for instance:

const username : myLib.TextField = new myLib.TextField();

How can I achieve this?

  1. Is it possible to create a declaration file automatically?
  2. When no, how can I create a declaration file manually? How is it structured?

I tried tsc --declaration src\ts\my-lib.ts. Then a my-lib.d.ts file was created but also declaration files for all imported components, so buttond.d.ts, textfield.d.ts and dropdownMenu.d.ts.

Also my declaration file for my-lib.ts looks pretty the same than the original file (because its all about import / export and no type or function declarations). So I do not think that this file would help me.

My .tsconfig file:

{
    "compilerOptions": {
        "forceConsistentCasingInFileNames": true,
        "noImplicitReturns": true,
        "strict": true,
        "noUnusedLocals": true,
        "target": "es5",
        "sourceMap": true,
        "declaration": true,
        "emitDeclarationOnly": true,
    },
    "lib": [
        "umd"
    ],
}
1 Answers

As suggested in one of the comments, a possible solution to this issue can be: dts-bundle-generator. It takes typescript code and bundles it into a single file, it also adds the umd namespace if used with --umd-module-name flag. https://github.com/timocov/dts-bundle-generator

Related