在 ASP.NET Core 網站整合 TypeScript 與 Vue
在 Visual Studio 2022 支援 Vue 前端的 template後,我試著建立專案看了一下架構,發現它就是標準的 Vue Project,還得另外加 Web API 專案才是一個完整的網站專案。試著搜尋一下在現有 ASP.NET Core 整合 Vue 的方法,發現沒有文章完整解說該怎麼辦,於是我就只好一步一腳印的找資料跟測試網站,以下為筆者記錄的筆記:
首先開一個 ASP.NET Core 專案,然後加入如下圖所示的套件,好讓 Visual Studio 可以編譯 TypeScript 檔案:
接著要讓 TypeScript 檔可以呼叫 Vue 的函式,就需要一個 npm 設定檔來設定並下載 Vue 的 ts 型別定義檔案:
新增 package.json 後,修改如下:
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"@types/vue": "2.0.0",
"@babel/types": "7.17.0"
}
}
如果遇到修改 package.json 檔後,在寫 TypeScript 時 intellisense 還是失效,可以在專案底下執行下列指令:
npm i --save-dev @types/vue
之後是加入 Vue 的 js 檔案,選擇”新增用戶端程式庫”選項,如下圖安裝所需的檔案:
接下來新增 tsconfig.json 檔,設定如下:
{
"compileOnSave": true,
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "ES6",
"module": "ES2015",
"moduleResolution": "Node",
"allowJs": true,
"outDir": "wwwroot/js"
},
"exclude": [
"node_modules",
"wwwroot"
]
}
接下新增 app.ts 檔,程式碼如下:
import { defineComponent, createApp } from 'vue';
let v = defineComponent({
name: "app2",
data() {
return {
x: "aaa3",
y: "aaa4"
};
},
methods: {
a: function (): number {
return 1;
},
b: function (): string {
return "Hello World!!";
}
},
computed: {
add: function () {
return this.x + this.y;
}
}
});
export function GetVueObject(divName: string): any {
return createApp(v).mount(divName);
}
接下來修改前端 index.cshtml 檔,新增下列程式碼:
@section Scripts{
<script type="importmap">
{ "imports": {
"vue": "/lib/vue/vue.esm-browser.js"
} }
</script>
<script type="module" src="~/js/app.js"></script>
<script type="text/javascript" src="~/js/library.js"></script>
<script type="module">
import { GetVueObject} from "./js/app.js";
var vueApp = GetVueObject("#app");
console.log(vueApp);
</script>
}
<div id="app">
<label></label><br />
<label></label>
</div>
之後執行網站,就會顯示 x 跟 y 的屬性資料,收工。
參考資料