June 22, 2023

Compile TypeScript code with ASP.NET Web Applicaton Project

In the last post we have seen how to configure TypeScript code with ASP.NET Core Project. In this post we will configure the TypeScript in an ASP.NET Web Applicaton Project (.Net Framework).

Suppose we already have an ASP.Net Web Application Project.

Inside Scripts folder, Create a new TypeScript file, say app.ts.

Add the folowing code:

sayHello(name: string) {
	console.log("Hello " + name);
}

As we changed some configurations for TypeScript compiler in the last post, we will do the same here. Select Add New Item, and choose TypeScript Configuration File and use the default name of tsconfig.json. Replace the content in tsconfig.json file with following.

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": false,
    "target": "ES2015",
    "allowJs": false,
    "inlineSourceMap": true,
    "sourceRoot": "./",
    "outDir": "Scripts",
    "inlineSources": true,
    "lib": [ "es2015", "es2016", "dom", "es2018.promise" ]
  },
  "exclude": [
    "./Scripts/JS"
  ],
  "compileOnSave": true
}

It will exlude the files for compilation which will be palced inside Scripts/JS folder as mentioned in exclude section above. It also tells the compiler to copy the output js files in Scripts folder (mentioned by outDir key). We need to use the same path when referencing the js file in HTML.

<script src="Scripts/app.js"></script>

Sometimes you might also need to manually add a TypeScript compiler task to your website project. Edit [YourProjectName].csproj file, and add the following <Target> element before the </Project> closing tag:

<Target Name="TypeScriptCompile" BeforeTargets="Build">
  <Exec Command="tsc" />
</Target>

Save the changes, and reload the project.

Now we have all setup with TypeScript, we can write TypeScript code and it should work.

Related Post(s):

No comments:

Post a Comment