How to include Typescript into HTML files?

Topics: General
Oct 10, 2012 at 9:49 AM

Is there any way how to include typescript into html files and get type checking there? I use VS 2012.

Oct 10, 2012 at 1:03 PM

You can't actually include a TypeScript file into a HTML document. You have to compile it to native JavaScript first.

If you still want to include directly *.ts files, there's a way using .htaccess and a server-side language.
Here is a complete example which works really great for me:

Oct 10, 2012 at 1:06 PM
czb wrote:

Is there any way how to include typescript into html files and get type checking there? I use VS 2012.

Tangentially to that question, why do you want to have script embedded in the HTML? It's really a bad practice, but I understand that there are sometimes reasons for wanting to do it.

Oct 10, 2012 at 3:32 PM

it is possible actually... the typescript compiler is just JS and you can scan for script tags with, say type="text/typescript" and run the compiler on whats inside it. You'd still have to include the typescript compiler as js and it would be slow so at that point you might as well just not do it at all. But it is still fun. The coffeescript website has an example of doing this in coffeescript, same principle here really.

Oct 31, 2012 at 3:38 PM

This is exactly what TypeScript Compile is doing. You just put your TS code into <script type="text/typescript" src="..."></script> tags and it get compiled into JS on-the-fly. It is done only once a session and the JS output is cached, so it's really fast.

Nov 2, 2012 at 11:44 AM

I have also started a project which aims to provide interfaces for multiple languages to the TypeScript compiler:
You can compile/run pure strings, script blocks, TypeScript code from external resources and even output the declaration code which was generated.

JavaScript (but completely written in TypeScript) and PHP interfaces are currently implemented.


To be honest, your ts-compile project brought me to this idea. I've completely rewritten the JS/TS part from scratch.
But how did you minify typescript.js down to 249 kb? I've tried Google Closure Compiler and YUI Compressor.

Nov 5, 2012 at 1:27 AM

@ComFreek: Good work, although I would add the lib.d.ts reference file as the first compilation unit, in order to get rid of compilation errors, like:
{"start":-1,"len":0,"msg":"The name 'IArguments' does not exist in the current scope","block":0}

I used Packer to compress it, but it can be even smaller by gzipping it on a server.