Wednesday, 3 November 2021

How to compile/build a TypeScript library that uses no NodeJS API/Module dependency to support browser

I wrote a few code that use plain browser Javascript APIs only and can be run well within browser HTML (served by IIS Server or Chrome Extensions). Now I want to contribute to the community by writing a library I have not seen on the market yet. However looking at current solutions, I am at loss at how a project is even built (WebPack/Browserify etc). A side note: I never actually work with NodeJS/NPM before.

For example I have this TypeScript project with the main file AwesomeClass.ts like this:

import { Helper1 } from "./Helper1.js";
import { Helper2 } from "./Helper2.js";

export class AwesomeClass {
    doSomething() {
        new Helper1().doSomething();
        new Helper2().doSomething();
    }
}

When built with tsc (I use VS Code as IDE), I can perfectly put this inside an Javascript module and browser can run it.

import { AwesomeClass } from "./AwesomeClass.js";

// Do something with AwesomeClass

So my question is, how do I build and distribute AwesomeClass? Maybe no NPM needed, but from a CDN? Ideally, I think somehow I should have the following output in a dist folder and developer can refer them either by hosting the files by themselves or use a CDN:

  • awesomeclass.js: For those who want to just use AwesomeClass without module feature (I think it's called UMD?). I.e. expose the AwesomeClass to global scope.
  • awesomeclass.es6.js: For those who want to use AwesomeClass by using import statement, like import { AwesomeClass } from "https://cdn.example.com/awesomeclass.es6.js";. I like this approach best and want to use this.
  • I should have something like awesomeclass.d.ts so those using TypeScript can use it. This one is especially tricky because so far I still don't understand how to make it work for 2nd scenario. TypeScript cannot get the type from an import statement from Javascript, and even ignoring that, I cannot get any typing for import statements.

In all cases, I would rather have only one js/ts file packed together if possible but not a deal breaker if I cannot (i.e. user will have to download Helper1.js and Helper2.js as well if I cannot).

Here's my current tsconfig.json:

{
    "compileOnSave": true,
    "compilerOptions": {
        "noImplicitAny": true,
        "target": "ES2020",
        "module": "ES2020",
        "declaration": true
    },
    "exclude": [
        "node_modules"
    ]
}


from How to compile/build a TypeScript library that uses no NodeJS API/Module dependency to support browser

No comments:

Post a Comment