TypeScript without NodeJS - Compiling TypeScript with Deno

TypeScript extends JavaScript with type safety, but requires compilation. Unfortunately, official TypeScript depends on a NodeJS environment.

Hugo (static website generator) has a pipe command js.Build through the bundled ESBuild (implemented in Go). However, using it is an absolute hassle, and limited. I struggled quite a bit to try and use it adequately.

All I want to do is implement ts files alongside content page bundles, and produce one page and one worker JavaScript file. I was unable to do so.

Deno is a JavaScript and TypeScript runtime implemented in Rust. The CLI also allows bundling TypeScript source files into JavaScript files, effectively compiling them.

Getting it to work was an adventure too. The Deno bundle runtime environment can use and include various libraries/namespaces. Targeting the webbrowser or web worker, the default was not sufficient. Adding the DOM namespace caused conflicts with the default deno.window.

To use Deno on the command line to compile ts files, which may include other modules:

Create tsconfig.dom.json

{
    "compilerOptions": {
        "lib": ["deno.ns", "dom"]
    }
}

Create tsconfig.worker.json

{
    "compilerOptions": {
        "lib": ["deno.ns", "deno.worker"]
    }
}

Create build script

A script that will

  1. compile the ts modules into js modules
  2. compile the ts page and worker files

On Windows, build.bat (example, with modules folder, tsconfig files in current folder, and target in parent folder)

@echo off

deno bundle --config tsconfig.dom.json    modules/CRC32.ts    modules/CRC32.js
deno bundle --config tsconfig.dom.json    modules/FileView.ts modules/FileView.js

deno bundle --config tsconfig.worker.json worker.ts ../worker.js
deno bundle --config tsconfig.dom.json    page.ts ../page.js

Integration with Hugo? Back to Type Comments

While this worked, when working on a website with Hugo, it’s quite annoying to have to run builds manually.

In the end, I went back to annotating JavaScript code with type comments. Then I work with simple JS files, but still get type checking and completion in VS Code.

/**
 * @param {string} param1
 * @param {number} param2
 * @returns {Uint8Array}
 */
function example(param1, param2) {
}