Declaring UMD module in TypeScript: Generating typings for a UMD module authored in TypeScript

For the purpose of learning, I created a small TypeScript library and utilized webpack to generate a JS UMD module from my TypeScript code.

Here is the structure of my project:

|-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

The my-lib.ts file contains the following code:

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

export {
    Button,
    TextField,
    DropdownMenu,
}

By including my-lib.min.js in HTML via src, I can use my components like this: (The UMD module is named with webpack as myLib).

const username = new myLib.TextField();

Now, I want to use my library in a new TypeScript project without delivering the TS files, but using only the declarations to treat it like a JS UMD module:

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

How can I achieve this?

  1. Is it possible to generate a declaration file automatically?
  2. If not, how can I manually create a declaration file? What should be its structure?

I attempted

tsc --declaration src\ts\my-lib.ts
, which created a my-lib.d.ts file along with declaration files for all imported components like buttond.d.ts, textfield.d.ts, and dropdownMenu.d.ts.

The declaration file for my-lib.ts appears similar to the original file as it mainly consists of import/export statements without type or function declarations, making it seem ineffective for my purpose.

Here is my .tsconfig file:

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

Answer №1

To address the problem mentioned in the comments, a potential fix could be to utilize the tool called dts-bundle-generator. This tool is designed to compile TypeScript code into a single file and can even include the umd namespace by using the --umd-module-name flag. Visit dts-bundle-generator on GitHub

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The variable "prisma" is not defined in this context - Next.js version 14

While working with Prisma and next.js 14, I encountered an issue with the Stripe payment API. The error message ReferenceError: prisma is not defined popped up. How can I resolve this? import { NextApiRequest, NextApiResponse } from "next" import ...

Does anyone know how to retrieve the application version or import the package.json file? Can't seem to find the solution on

I need to display the version from the package.json file in my Angular application. To import it, I allowed importing json by adding a few extra lines in tsconfig.json: { "compilerOptions": { "module": "commonjs", ...

Is webpack-dev-server necessary when working with a node server such as express?

I have been exploring tutorials on creating an isomorphic app with express and react, but I'm feeling a bit overwhelmed by the webpack-dev-server. In one of the webpack tutorials, they mention the webpack-dev-server: This sets up a small express ser ...

What is the best way to access the input element of ng-content from the parent component?

Creating a unique component in the following structure <div class="custom-search-field" [ngClass]="{'expanding': expanding}"> <ng-content></ng-content> </div> When using this component, users are expected to include ...

Mastering the art of bi-directional data binding with nested arrays in Angular

Imagine you have a to-do list with various tasks, each containing multiple subtasks. You want the ability to change the subtask data, but why is Angular not properly two-way binding the data for the subtasks? HTML <div *ngFor="let task of tasks"> ...

Having trouble with data types error in TypeScript while using Next.js?

I am encountering an issue with identifying the data type of the URL that I will be fetching from a REST API. To address this, I have developed a custom hook for usability in my project where I am using Next.js along with TypeScript. Below is the code sni ...

Combine both typescript and javascript files within a single Angular project

Is it feasible to include both TypeScript and JavaScript files within the same Angular project? I am working on a significant Angular project and considering migrating it to TypeScript without having to rename all files to .ts and address any resulting er ...

What is the best way to implement a useState within a context for testing with jest?

function CustomComponent() { const {val, change} = useContext(ProviderContext) return ( <TextField> onChange={({target}) => { change(target) }} value={val} </TextField> ); } describe('test', ( ...

Type of tuple without a specific order

Exploring Typescript typings has led me to ponder how to create a type that is a tuple with unordered element types. For example: type SimpleTuple = [number, string]; const tup1: SimpleTuple = [7, `7`]; // Valid const tup2: SimpleTuple = [`7`, 7]; // &ap ...

After updating to ionic-native 2.5.1, encountering TypeScript Error TS1005 in Ionic 2

After updating to the latest version of ionic-native (2.5.1) in my ionic 2 project, I am encountering Typescript errors when running "ionic serve" in my terminal. I have attempted to update the typescript version to 2.x but to no avail. Any assistance woul ...

The Ionic 2 application encountering issues with building after the installation of the Facebook login plugin

Currently, I am in the process of developing a Hybrid app using Ionic-2 on Ubuntu. I encountered an issue when trying to add Facebook login functionality to my app. After installing the Facebook plugin, the app build fails. However, if I remove the Faceb ...

Protractor Browser Instance Failure

We have encountered an issue with our UI suite failing in Chrome during the login process. Initially, we thought it might be due to upgrading to Chrome 79, as the problems arose simultaneously. Interestingly, the login functionality still works smoothly in ...

Creating a Checkbox-enabled Muiv5 TreeView for an array of objects: Step-by-step guide

Currently, I am utilizing the muiv5 treeview component to construct a treeview dropdown. Unfortunately, the component does not have built-in checkbox support for selection/deselection. However, after conducting some research, I managed to find a somewhat s ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

Verification for collaborative element

I am currently working on creating a shared component for file uploads that can be reused whenever necessary. Interestingly, when I include the file upload code in the same HTML as the form, the validation functions properly. However, if I extract it into ...

"Angular encountered an error while attempting to access the property 'data' from an undefined

I'm encountering an issue when trying to retrieve data from a JSON file. Upon clicking a button to display the data in a textarea, the first click does not yield any result, but subsequent clicks work as expected. The program functions by fetching an ...

What is the proper way to address the error message regarding requestAnimationFrame exceeding the permitted time limit?

My Angular application is quite complex and relies heavily on pure cesium. Upon startup, I am encountering numerous warnings such as: Violation ‘requestAnimationFrame’ handler took 742ms. Violation ‘load’ handler took 80ms. I attempted to resolve ...

Transmit a form containing a downloaded file through an HTTP request

I am facing an issue with sending an email form and an input file to my server. Despite no errors in the console, I can't seem to upload the file correctly as an attachment in the email. post(f: NgForm) { const email = f.value; const headers = ...

Animating Angular ng-template on open/close state status

I am looking to add animation when the status of my ng-template changes, but I am unable to find any information about this component... This is the code in my report.component.html <ngb-accordion (click)="arrowRotation(i)" (panelChange)="isOpen($even ...

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...