Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

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@4.9/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());
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top