Enable TypeScript compilation in any project, for example a class library in .NET 4.x
Posted: (EET/GMT+2)
TypeScript is a great language, and if I get to choose, I'm using it always when JavaScript is needed. TypeScript can be useful in many different project types, so it's good to know that you can compile TypeScript in almost any Visual Studio project. This includes even .NET 4.x class libraries, for instance. To add TypeScript building functionality, add the suitable MSBuild targets to your project via NuGet, and then add a tsconfig.json file with configuration. Next time you build, the TypeScript compiler (TSC) will also run.
Here are the quick steps:
1) Add the MSBuild package to your project:
Install-Package Microsoft.TypeScript.MSBuild
2) Add a tsconfig.json to the project root (customize to your liking):
{
"compilerOptions": {
"target": "es5",
"outDir": "wwwroot/js",
"sourceMap": true,
"strict": true
},
"include": [ "Scripts/**/*.ts" ]
}
3) Add your .ts files under "Scripts" (or any folder you prefer):
// Scripts/hello.ts
export function greet(name: string) {
return "Hello, " + name;
}
4) Build the project. MSBuild runs "tsc" using your tsconfig.json and writes .js (and .map) files to outDir.
If you want the .csproj to make the TypeScript folder explicit, add:
<ItemGroup> <TypeScriptCompile Include="Scripts\**\*.ts" /> </ItemGroup>
Some things to note:
- TypeScript build works even in non-web projects; the output is just files.
- If you have Node installed, you can also run "tsc" from npm scripts with watch mode, while MSBuild handles automated CI builds.