How to compile TypeScript web app with node modules into one JavaScript file using CLI?

Viewed 267

What is the simplest and fastest way to set up a TypeScript web application with node modules, that compiles into one JavaScript file that can be called from HTML?

For example, if I have the following project structure:

├── node_modules
│   └── mathjs
│   └── (dependencies, etc.)
├── public
│   └── index.html
│   └── app.js
├── src
│   └── app.ts
├── package-lock.json
└── package.json

app.ts contains the following code with node modules and typing imports:

import math from "mathjs";
import { Matrix } from "mathjs";

const point: Matrix = math.matrix([ +1, +1, +1 ]);
// etc...

How can I make it so that app.ts and all its dependencies are compiled into a single file app.js in the public directory such that, it can be included at the bottom of the body tag in index.html and be run in a browser?

<script type="module" src="/app.js"></script>

In other words, what CLI tools can I use to compile this project for the web?

I have spent hours trying to research and get something to work (without copying and pasting directly from node_modules) and have not been able to get anything to work. Any help will be greatly appreciated!

Edit: Parcel is exactly what I was looking for.

1 Answers

The simplest thing you could do using only the typescript compiler is to use system or amd modules inside the tsconfig.json and also use the outFile (this option works only with system or amd modules) option in order to concatenate all the files of your app into a bundle that you can use later with something like system.js. You can read more about it here.

I just want to note that with the standard tsconfig configuration the node_module dependencies won't be included inside the outFile config option bundle and you will have to configure systemJS to load them when separately. Maybe it is possible to include them as well but I haven't played around with the tsc options to achieve something like that, but you can try. Please do let me know if you succeed.

Btw if you decide to go with this approach and not use an external module bundler like webpack or rollup I suggest that you don't use the outFile option to bundle everything into one file because sometime ago I was struggling to make systemJS work with the out bundle but when I used separate files everything was working just fine.

Related