June 18, 2023

Compile TypeScript code with ASP.NET Core

In this post I will explain the steps we need to setup TypeScript into an ASP.NET Core project.

Lets suppose we already have an ASP.Net Core Project.

We need to install Nuget Package Microsoft.TypeScript.MSBuild to build typescript code/files.

Create a new file named app.ts.

Add the folowing code:

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

We need to tell TypeScript by configuration settings to direct the behavior for compilation. 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.

{
  "compileOnSave": true,
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "wwwroot/ts_build"
  },
  "exclude": [
    "./node_modules",
    "./wwwroot",
  ],
  "include": [
    "./TypeScripts"
  ]
}

It will include any typescript file for compilation which will be palced inside TypeScripts folder as mentioned in include section above. It also tells the compiler to copy the output js files in wwwroot/ts_build folder (mentioned by outDir key). We need to use the same path when referencing the js file in HTML.

<script src="~/ts_build/app.js"></script>

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

References:

Related Post(s):

No comments:

Post a Comment