问题
I want to be able to have inline TypeScript in an ASPX (or Razor) page that is converted to Javascript when the page compiles.
So:
<script type="text/typescript" runat="server">
...
</script>
Becomes...
<script type="text/javascript">
...
</script>
It should happen at the same point that @
or <% %>
blocks are converted.
This should be possible at run time with some kind of page post-processing, but that won't generate exceptions at compile time - I want to find errors in the script at the same time as any C# code.
Ideally TypeScript intellisense and the like should work in the inline <script>
block, which makes me think that this should be a VS2012 extension.
Is there any way to do this?
回答1:
The short answer is no.
You could write a TypeScript file and paste the compiled JavaScript in, but that's as close as you'll get. One practical problem would be that if the compiler transformed your TypeScript into JavaScript, you would lose your TypeScript code. This is why you have a TypeScript file and a JavaScript file.
What's the compelling reason to put the script inline rather than referencing an external script - maybe there is another solution to your problem that doesn't require inline scripts?
回答2:
You could create a server-control that compiles the code at runtime, and caches it:
[DefaultProperty("Text")]
[ToolboxData("<{0}:TypeScript runat=server></{0}:TypeScript>")]
public class TypeScript : WebControl
{
public string Text { get; set; }
protected override void RenderContents(HtmlTextWriter output)
{
output.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
if (!string.IsNullOrEmpty(this.ID))
{
output.AddAttribute(HtmlTextWriterAttribute.Id, this.ID);
}
output.RenderBeginTag("script");
output.Write(CompileToJavaScript(Text));
output.RenderEndTag();
}
private string CompileToJavaScript(string typeScript)
{
// TODO: Call tsc with the code, and return the result.
}
}
You might be able to compile tsc.js with JScript.NET, if you care to implement the IO-layer, and weed out some JScript.Net (not JavaScript) syntax errors.
回答3:
have a work around for it, what I do is declare the variables needed from razor in a script tag
<script type="text/javascript"> //Razor variables initialized here and declared in the TypescriptFile.ts file var url = "@Url.Action("NewRequest", "Request")"; </script>
next declare the url variable in the Typescript file
//TypescriptFile.ts declare var url: string; alert(url);
use it
sad to see that Visual Studio 2013 still does not provide server side support.
回答4:
Although it's not a real solution to your problem, but why don't you leave your TypeScript code as is in <script type="text/typescript">
and use Typescript Compile to have it compiled at runtime?
来源:https://stackoverflow.com/questions/13496911/using-typescript-with-an-inline-server-side-script-block-and-asp-net