How to compile TypeScript code in the browser?

Solution 1:

You can use typescript-script : https://github.com/basarat/typescript-script

However do not do this in production as it is going to be slow.

You can use webpack (or a similar module bundler) to load npm packages in the browser.

Solution 2:

Transpiling ts to js is as simple as loading the typescriptServices.js file from typescript repo or npm, and using it's window.ts.transpile(tsCode)

JSFiddle

<script src="https://unpkg.com/typescript@latest/lib/typescriptServices.js"></script>
<script>
const tsCode = 'let num: number = 123;';
const jsCode = window.ts.transpile(tsCode);
document.write(jsCode);
</script>

Outputs:

var num = 123;

You can also pass the ts compiler options object as second argument to ts.transpile() to specify whether output js should be es2020, es5, es6, and other stuff, though for meaning of values you'll likely have to dive into the source code.




Since this question got re-opened (just as planned >:D), I'm also re-posting my comment here.

@basarat's solution was great; even though his lib is outdated and abandoned, it helped me a lot in writing another, self-sufficient modern lib with support for sub-dependencies: ts-browser

Usage: (given you use relative paths in all your ts files)

<!-- index.html -->
<script type="module">
    import {loadModule} from 'https://klesun.github.io/ts-browser/src/ts-browser.js';
    loadModule('./index.ts').then(indexModule => {
        return indexModule.default(document.getElementById('composeCont'));
    });
</script>
// index.ts
import {makePanel} from './utils/SomeDomMaker'; // will implicitly use file with .ts extension

export default (composeCont) => {
    composeCont.appendChild(makePanel());
};