--- lang: ja-jp breaks: true --- # Visual Studio で TypeScript を使用する 2021-09-04 > Visual Studio で npm パッケージを管理する > https://docs.microsoft.com/ja-jp/visualstudio/javascript/npm-package-management?view=vs-2019#aspnet-core-projects > TypeScript コードのコンパイル (ASP.NET Core) > https://docs.microsoft.com/ja-jp/visualstudio/javascript/compile-typescript-code-nuget ## Node.js をインストールしていない場合は、Node.js Web サイトから LTS バージョンをインストールする https://nodejs.org/en/download/ ## npm サポートをプロジェクトに追加する (`ASP.NET Core`) > https://docs.microsoft.com/ja-jp/visualstudio/javascript/npm-package-management?view=vs-2019#aspnet-core-projects ![](https://i.imgur.com/1okYPKA.png) ```json= { "version": "1.0.0", "name": "asp.net", "private": true, "devDependencies": { "@types/jquery": "3.5.6" } } ``` ![](https://i.imgur.com/7itOT0W.png) ![](https://i.imgur.com/1EQNXdT.png) :::warning Razorクラスライブラリ `Sdk="Microsoft.NET.Sdk.Razor"` ![image](https://hackmd.io/_uploads/BJeG0qoaC.png) の場合は、GUIから`npn構成ファイル`を追加できないので以下のコマンドを実行する。 ```shell= npm init ``` ::: ## 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" ] } ``` :::info この設定で、 `scripts` フォルダ配下に *.ts ファイルを作成し保存すると、`wwwroot/js/*` 配下に `*.js` ファイルが作成される。 ::: ## Blazor で TypeScript を使用する ### `@types/blazor__javascript-interop` を導入する > @types/blazor__javascript-interop > https://www.npmjs.com/package/@types/blazor__javascript-interop > DefinitelyTyped/DefinitelyTyped > https://github.com/DefinitelyTyped/DefinitelyTyped > ```shell= npm install --save-dev @types/blazor__javascript-interop ``` :::info `DotNet.DotNetObject` が使用できるようになる。 ![image](https://hackmd.io/_uploads/S1tw1jj6R.png) ::: :::info 使い方の例 ```typescript= _dotnetReference: DotNet.DotNetObject = null; constructor( dotnetReference: DotNet.DotNetObject, numberOfConsecutiveScans: number = null ) { this._dotnetReference = dotnetReference; } async callDotNetMethod() { await this._dotnetReference.invokeMethodAsync( "OnResultRowValuesChanged", this._scanResultRowValues ); } ``` ::: ###### tags: `TypeScript` `Visual Studio` `npn` `ASP.NET Core` `Node.js`