--- lang: ja-jp breaks: true --- # ASP.NET Core で TypeScriptを使う Visual Studio 2021-05-11 > チュートリアル: Visual Studio での TypeScript を使用した ASP.NET Core アプリの作成 > https://docs.microsoft.com/ja-jp/visualstudio/javascript/tutorial-aspnet-with-typescript?view=vs-2019 ## `ASP.NET Core Webアプリ MVC` プロジェクトを作成 ![](https://i.imgur.com/921ssVF.png) ## NuGet パッケージ `Microsoft.TypeScript.MSBuild` の追加 ![](https://i.imgur.com/FhtufcH.png) ## `TypeScript JSON 構成ファイル` を追加 `tsconfig.json` ファイルを追加します。 ![](https://i.imgur.com/tFfW303.png) ```json= { "compileOnSave": true, "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false, "sourceMap": true, "target": "es5", "outDir": "wwwroot/js" }, "include": [ "scripts/**/*" ], "exclude": [ "node_modules", "wwwroot" ] } ``` ## scripts/app.ts ファイルを追加 ![](https://i.imgur.com/Jtc82X9.png) ```typescript= function TSButton() { let name: string = "Fred"; document.getElementById("ts-example").innerHTML = greeter(user); } class Student { fullName: string; constructor( public firstName : string, public middleInitial : string, public lastName : string ) { this.fullName = firstName + " " + middleInitial + " " + lastName; } } interface Person { firstName: string; lastName: string; } function greeter(person: Person) { return "Hello, " + person.firstName + " " + person.lastName; } let user = new Student("Fred", "M.", "Smith"); ``` 保存すると、`outDir` で指定した、`wwwroot/js/app.js` ファイルが生成される。 ![](https://i.imgur.com/lxv2WWd.png) ## Views/Home フォルダーを開き、Index.cshtml を変更 ```htmlembedded= @{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div> <div id="ts-example"> <br /> <button type="button" class="btn btn-primary btn-md" onclick="TSButton()"> Click Me </button> </div> ``` ## Views/Shared フォルダーを開き、 _Layout.cshtml を変更 ```htmlembedded= ・・・ <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> <script src="~/js/app.js"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html> ``` ## 実行確認 ![](https://i.imgur.com/gZ9Ad8G.png) ###### tags: `ASP.NET Core` `TypeScript` `Visual Studio`