It can be often useful to be able to deliver TypeScript files directly to the browser and to defer the transpilation to JavaScript until then. While this method has performance drawbacks, it is extremely useful when prototyping and performing experimentations.
The code, links, and a live example of this are available at .
Create an empty project directory and create the following package.json
inside it:
[package.json] { "scripts": { "lite-server": "lite-server" }, "devDependencies": { "lite-server": "^2.2.2", "systemjs": "^0.19.38", "typescript": "^2.0.3" } }
Running npm install
should get you ready to write code.
The TypeScript npm
package comes bundled with a transpiler. When combined with SystemJS as the designated transpilation utility, this allows you to serve TypeScript files to the client; SystemJS will transpile them into browser-compatible JavaScript.
First, create the index.html
file. This file will import the two required JS libraries: system.js
and typescript.js
. Next, it specifies the typescript as the desired transpiler and imports the top-level main.ts
file:
[index.html] <html> <head> <script src="node_modules/systemjs/dist/system.js"> </script> <script src="node_modules/typescript/lib/typescript.js"> </script> <script> System.config({ transpiler: 'typescript' }); System.import('main.ts'); </script> </head> <body> <h1 id="text"></h1> </body> </html>
Next, create the top-level TypeScript file:
[main.ts] import {article} from './article.ts'; document.getElementById('text') .innerHTML = article;
Finally, create the dependency TypeScript file:
[article.ts] export const article = "Cool story, bro";
With this, you should be able to start a development server with npm run lite-server
and see the TypeScript application running normally in your browser at localhost:3000
.
SystemJS is able to resolve module dependencies as well as apply the transpiler to the module before it reaches the browser. If you look at the transpiled files in a browser inspector, you can see the emitted files exist as vanilla JavaScript IIFEs (instantaneously invoked function expressions) as well as their coupled source maps. With these tools, it is possible to build a surprisingly complex application without any sort of backend file management.
Unless you're experimenting or doing a rough project, doing transpilation in the browser isn't preferred. Any computation you can do on the server should be done whenever possible. Additionally, all the clients transpiling their own files all perform highly redundant operations since all of them transpile the same files.