klumsy
klumsy

Reputation: 4261

How to compile TypeScript code in the browser?

Is it possible to run the TypeScript compiler in the browser for transpiling TS to JS 100% in the browser. The use case would be implementing an online TypeScript IDE that runs 100% client side and it has a "Play" button to execute the project. So I need to transpile the project to JavaScript in order for the browser to execute the code.

I presume it should be as simple as loading the relevant typescript JS files, creating an instance of the right class (compiler?) and calling a method or two.

What would be the means suitable to load the Compiler in the browser? Where is the TypeScript Compiler API Reference Documentation ? Where should I start digging in ?

This isn't asking for any specific tool, but ANY way to do this with this particular computer language, and thus is on topic.

Upvotes: 73

Views: 47197

Answers (3)

Klesun
Klesun

Reputation: 13673

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

JSFiddle

<script src="https://unpkg.com/typescript@latest/lib/typescript.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 like:

ts.transpile(tsxCode, { jsx: "react", target: "es2015" });

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';
    // language=file-reference
    const entryScriptPath = './index.ts';
    loadModule(entryScriptPath).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());
};

Upvotes: 34

Sean Bradley
Sean Bradley

Reputation: 3577

I wrote this specifically for the purpose of compiling TypeScript in the browser so that I could write quick and simple examples to share.

https://github.com/Sean-Bradley/text-typescript

Usage,

<script type="text/typescript">
    // Your TypeScript code here
</script>

And include dependencies.

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

A complete example you can copy/paste into a HTML doc and try locally.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>"text/typescript" example</title>
        <meta name="description" content="Transpiling and executing TypeScript in the browser" />
        <style>
            body {
                overflow: hidden;
                margin: 0px;
                font-size: 15vw;
            }
        </style>
        <script type="text/typescript">
            function foo(bar: string) {
                return "Hello " + bar;
            }

            let baz = "World!";

            document.getElementById("root").innerHTML = foo(baz);
        </script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
        <script defer src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>

And you can see it working here, right now, today.

https://editor.sbcode.net/f1f4b5a73ec40283d1ddb37bb1e71f7e4e31b487

Upvotes: 1

basarat
basarat

Reputation: 275895

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.

Upvotes: 26

Related Questions