74

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.

9
  • 8
    For many reasons, but yes for production code you wouldn't normally want to. But some reasons could be building a playground like that on typescriptlang.org, or in building a web IDE, or web based compiler, or maybe a compiler than then copies files to servers via cloud services. In my case i'm just looking for a pithy example without the full burden of TSC to do compilation of a single file. My scenario wasn't actually in the browser, but in a PowerShell script hosting the Chakra JS engine, but the simplest way to get there was a simple browser based script. Commented Apr 17, 2014 at 4:30
  • 6
    A comment, because the Q is closed: You're looking for the transpile() method on the default exported module of the Typescript npm package. import * as TS from 'typescript'; TS.transpile(sourceTS) -> returns transpiled JS. github.com/Microsoft/TypeScript/blob/master/lib/… Commented Oct 15, 2017 at 20:04
  • 16
    It's sad so many useful questions are closed as off-topic. You may ask about a string manipulation function as long as it is simple, like how to reverse a string. As soon as it is a complex function like transpile, it is off topic. Commented Aug 21, 2018 at 9:20
  • 2
    This is what I have: a typescript playground in the browser cancerberosgx.github.io/typescript-in-the-browser/… BTW I'm sad you have closed this question, since this kind of questions, although incorrect, are one of the few places when beginers can get started with compiler API which has insufficient high level docs, yet, i hope. thanks Commented Oct 25, 2018 at 3:02
  • 1
    I tried to answer this question here: stackoverflow.com/questions/46059313/… hope we can share more experiences and don't close that one too Commented Oct 25, 2018 at 4:05

3 Answers 3

37

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());
};
Sign up to request clarification or add additional context in comments.

8 Comments

I couldn't find the compiler options that does type check. window.ts.transpile('let num : number= "1232";', {noEmitOnError: true, strict: true}) But it wouldn't fail
Looks like ts.transpile/ts.transpileModule only does transpilation without type checking by design. There are possibly some other methods in window.ts that would allow type checking, but finding that out would require some research...
may it be, that "typescriptServices.js" is no longer available for TS versions 5.x and above? The latest one I could find was for 4.9.5. Is there an alternative?
It looks like this can be replaced by just using typescript.js github.com/microsoft/TypeScript/issues/50758
Answer to my own question - I needed to add const jsCode = window.ts.transpile(tsCode, { jsx: 'react'});
|
26

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.

6 Comments

Why would it be unsafe?
@DavidGiven I don't know why I thought that he will be serving TypeScript input by the user. So removed. Thanks!
For transpiling in the browser you don't need to do any hack - just include node_modules/typescript.js in your html file will allow you to use the COmpiler API. Here is a playground that transpile to js 100% in the browser : cancerberosgx.github.io/typescript-in-the-browser/…
I re-wrote it to a working up-to date lib last night for same cause. It also resolves import dependencies now.
Haha, @ArturKlesun, I did the same thing! Yours looks a bit more elegant (I flat-out did not allow circular dependencies), but how do you handle lib imports like lib.dom.d.ts? Is yours able to have typescript embedded in the html as you would js too? It's so funny we did this a week apart on a topic that hadn't been touched for over a year
|
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.