Tom Kris
Tom Kris

Reputation: 1227

Using TypeScript in cshtml files

I'm wondering is there any way to use TypeScript on Razor cshtml files?

For example, something like this

<script language="text/typescript">
/// typescript goes here
</script>

Upvotes: 29

Views: 14306

Answers (5)

Wouter Devinck
Wouter Devinck

Reputation: 63

You could manually compile the TypeScript files using tsc.exe and then add the resulting Javascript to your project or use a tool, such as Web Essentials that compiles on save.

As the compiler can be compiled to Javascript, you can also let the user's browser do the compilation on the fly (at the cost of performance and file size, the compiler is fairly big). An example of this approach is niutech's solution.

If you are using Bundling and Minification, I have just released an implementation of IBundleTransform that compiles TypeScript to Javascript. It is on GitHub and NuGet (Install-Package TypeScriptBundleTransform). If you are not yet using Bundling and Minification, it is worth a look!

Upvotes: 2

Manuel Schweigert
Manuel Schweigert

Reputation: 4974

I just checked with my favorite VS Extension: Web Essentials

They already included .ts file compilation on saving (it is recommended to also use the original plugin for Intellisense).

This obviously only works for .ts files, though. In my opinion, once you reach the complexity to choose typescript over javascript, you should use it in a separate file, anyways.

Upvotes: 5

niutech
niutech

Reputation: 29922

It's possible. I have developed TypeScript Compile - an automatic compiler of TypeScript to JavaScript on the fly. Have a try!

Upvotes: 19

Michael Sondergaard
Michael Sondergaard

Reputation: 1494

Let me add to Robs answer that it's technically possible to embed the typescript compiler in a page download, and have the browser compile code written in <script language="text/typescript"> tags.

Performance however, would be suboptimal and precompilation on the server would be preferred. Technically, there's nothing preventing a preprocessor from doing this either (T4 could do it).

Upvotes: 5

Rob
Rob

Reputation: 3516

TypeScript isn't a runtime; it's cross-compiled into JavaScript. As a result, you'll need to write your TypeScript, compile it, and then either include it within JavaScript script tags or as an external file.

Upvotes: 17

Related Questions