2024/03/31

[.NET] 如何在 ASP.NET Core 的專案整合 Vite 開發

前言

之前大多使用 Laravel 搭配 Vite 來做前端資源整合開發,由於 Laravel 生態系非常完整,也不太需要多做太多設定即可整合完成。

近期在 ASP.NET Core MVC 的專案使用 Vite 開發前端資源檔案,使用上卻不是那麼上手。尤其是在開發時期載入檔案的部分,在 Laravel 用 @vite 卻可輕易完成,便尋尋覓覓找到相近的整合套件。

環境

  • Visual Studio 2022 (v17.9.2)
  • ASP.NET Core (.NET 8)
  • Package: Vite.AspNetCore
  • Vite 5.2
  • Vue 3.4

專案開發步驟

  1. 建立 ASP.NET Core Web App (Model-View-Controller) 的專案
  2. 安裝 NuGet 套件: Vite.AspNetCore
  3. 加入 Vite 相關檔案: package.json, vite.config.js

package.json 檔案內容如下:

{
  "name": "netappwithvite",
  "version": "1.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "dependencies": {
    "vue": "^3.4.21"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^5.0.4",
    "vite": "^5.2.7"
  }
}

vite.config.js 內容如下:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

export default defineConfig({
    appType: 'custom',
    root: 'Assets',
    server: {
        port: 5173,
        strictPort: true,
        hmr: {
            clientPort: 5173
        }
    },
    resolve: {
        alias: {
            '~': path.resolve(__dirname, './Assets/js'),
            vue: 'vue/dist/vue.esm-bundler.js',
        },
    },
    build: {
        manifest: true,
        emptyOutDir: true,
        outDir: path.resolve(__dirname, './wwwroot/build'),
        rollupOptions: {
            input: {
                main: 'Assets/js/main.js',
            },
            output: {
                chunkFileNames: 'js/[name].js',
                entryFileNames: 'js/[name].js'
            }
        }
    },
    plugins: [vue()],
})

Source 會放在 Assets/js 裡

Output 會建立到 wwwroot/build 資料夾

  1. 建立 Assets/js/main.js 檔案
import { createApp } from 'vue'
import App from './components/App.vue'

createApp(App).mount('#app')
  1. 建立 Assets/js/components/App.vue 檔案
<script setup="">
</script>
<template>
    <h2>Hello .NET Core with Vite integrated</h2>
</template>
  1. 修改 Views/Shared/_Layout.cshtml

在 main 標籤加入 id="app",因為指定 Vue component 會載到這個區塊

  1. 接著在 Views/Home/Index.html 載入我要的內容及 main.js
<app></app>

@section Scripts {
<script type="module" src="~/build/js/main.js" asp-append-version="true"></script>
}
  1. 執行 npm run build 產生前端資源檔

  2. 執行網站,確認可以看到畫面出現 Hello .NET Core with Vite integrated 的內容

Vite 整合開發模式

  1. 修改 Program.cs 檔案

註冊 service

builder.Services.AddViteServices();

使用 service

if (app.Environment.IsDevelopment())
{
    app.UseViteDevelopmentServer(true);
}
  1. 修改 Views/_ViewImports.cshtml 檔案加入
@addTagHelper *, Vite.AspNetCore
  1. 修改 Views/Home/Index.cshtml 檔案 Scripts 區塊
@section Scripts {
    <environment names="Development">
      <script type="module" vite-src="~/js/main.js" asp-append-version="true"></script>
    </environment>
    <environment names="Staging,Production">
      <script type="module" src="~/build/js/main.js" asp-append-version="true"></script>
    </environment>
}

vite-src 或 vite-href 可以針對 script 或 link 的 style 檔案做開發關聯

這個 helper 會幫忙載入開發時的 Vite 資源

  1. appsettings.Development.json 檔案加上 Vite 設定,即會自動啟動 Vite Server
"Vite": {
  "Server": {
    "AutoRun": true
  }
}
  1. 執行看結果,然後修改 App.vue 的文字,可看到即時內容變更,我們的開發整合就完成了!

結語

隨著前端工具的改變,不時還是要研究整合前後端開發流程。學習的東西還是很多,從 JavaScript, jQuery, AngularJS, Vue 2, Vue 3 以及 Webpack, Vite 等各種打包,只能不斷精進跟著潮流走吧!這就是 Web 開發著的人生啊~

若你的專案本來就是前後端分離,前端是 html,而後端只有 Web API,那麼在 Microsoft Learn 教學課程:在 Visual Studio 中使用 Vue 建立 ASP.NET Core 應用程式 在 Visual Studio 2022 有相關直接建立的專案樣版可以使用