Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed TypeScript code in an HTML document

Tags:

typescript

Is it possible to embed TypeScript code in a web page? I want to embed TypeScript code inside script tags, like this (so that it is automatically compiled to Javascript):

<script type = "text/typescript">     //TypeScript code goes here </script> 
like image 548
Anderson Green Avatar asked Dec 24 '12 00:12

Anderson Green


People also ask

Can we include TypeScript in HTML?

A JavaScript library has already been developed for this purpose - it's called TypeScript Compile, and it allows typescript to be embedded in HTML (as shown above.)

Can we write TypeScript in script tag?

You can't use ts in HTML. If you want to do it you must do that in a separated file, use a transpiler and link the generated JS file inside the HTML.


2 Answers

Actually there are several projects that allow you to use TypeScript code like that - TypeScript Compile, ts-htaccess.

The catch here is that .ts code should be compiled into JavaScript - it can be done either at client-side (slow; the whole TSC should be loaded into the client as well) or at server-side (obviously faster, and it's far easier to leverage the cache on the compiled code).

like image 67
raina77ow Avatar answered Sep 23 '22 23:09

raina77ow


This is a version I wrote that directly uses the version from Microsoft/TypeScript/master so it always stays up to date: https://github.com/basarat/typescript-script

You can even point ts to any other TypeScript version you might have and it will work fine 🌹

like image 44
basarat Avatar answered Sep 21 '22 23:09

basarat