首页 文章 文章详情

创建一个基于Vite+Alpine.js+Basecoat+Tailwind的Asp.Net MVC站点

来源:本站 {{likeCount}} {{commentCount}} 评论 2026-05-25 04:31:58

基于 .NET 10.0 的现代化 ASP.NET Core MVC 应用,完整集成 Vite.AspNetCore 2.4.1

✨ 功能特性

功能状态说明
自动启动 Vite Dev Server运行 dotnet run 即可
环境自动检测开发/生产自动切换资源来源
HMR 热模块替换保存即刷新,无需手动刷新
统一的 Tag Helper使用 vite-src / vite-href
Manifest 文件支持生产环境使用哈希文件名

技术栈

  • ASP.NET Core MVC 10.0 - Web 应用框架
  • Vite 8 - 现代化前端构建工具
  • Alpine.js 3 - 轻量级前端交互框架
  • Basecoat - 基于 Tailwind 的组件库
  • Tailwind CSS 4 - 原子化 CSS 框架
  • Vite.AspNetCore 2.4.1 - 官方 Vite 与 ASP.NET Core 集成库

项目结构

ViteMvcApp/
├── ClientApp/          # 前端源文件
│   ├── main.js        # 入口文件
│   └── styles.css     # 样式文件
├── Controllers/       # MVC 控制器
├── Models/            # 数据模型
├── Views/             # MVC 视图
│   ├── Shared/        # 共享视图
│   │   └── _Layout.cshtml  # 主布局(使用 Vite Tag Helper)
│   └── _ViewImports.cshtml # 导入 Tag Helper
├── wwwroot/           # Web 根目录
│   └── dist/         # Vite 构建输出
├── Program.cs         # 应用入口(集成 Vite.AspNetCore)
├── ViteMvcApp.csproj # 项目文件
├── vite.config.js    # Vite 配置
└── appsettings.json  # 应用配置(含 Vite 配置)

🚀 快速开始

开发模式(一键启动)

cd ViteMvcApp
dotnet run

这会自动

  1. 启动 ASP.NET Core 应用 (http://localhost:5246)
  2. 启动 Vite 开发服务器 (http://localhost:5173)
  3. 建立 HMR WebSocket 代理
  4. 应用启动成功!🎉

访问:http://localhost:5246

生产构建与运行

cd ViteMvcApp

# 1. 构建前端资源(生成 manifest 和哈希文件)
npm run build

# 2. 运行生产模式应用
dotnet run --environment Production

# 或发布应用
dotnet publish -c Release

📝 配置详解

1. Program.cs - Vite.AspNetCore 集成

using Vite.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

// 1. 注册 Vite 服务
builder.Services.AddControllersWithViews();
builder.Services.AddViteServices();  // ✅

var app = builder.Build();

// 2. 开发模式:启用 Vite 开发服务器和中间件
if (app.Environment.IsDevelopment())
{
    app.UseWebSockets();  // ✅ 必须,支持 HMR
    app.UseViteDevelopmentServer(true);  // ✅ true = 使用内置中间件
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapStaticAssets();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}")
    .WithStaticAssets();

app.Run();

2. appsettings.json - Vite 配置

{
  "Vite": {
    "Manifest": ".vite/manifest.json",
    "PackageManager": "npm",
    "Server": {
      "AutoRun": true,       // ✅ 自动启动 Vite Dev Server
      "Port": 5173,          // Vite 端口
      "Https": false,        // 是否使用 HTTPS
      "ScriptName": "dev"    // npm script 名称
    }
  }
}

3. _ViewImports.cshtml - Tag Helper 导入

@using ViteMvcApp
@using ViteMvcApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Vite.AspNetCore  <!-- ✅ 启用 Vite Tag Helper -->

4. _Layout.cshtml - 使用 Tag Helper

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - ViteMvcApp</title>
    
    <!-- ✅ 使用 Vite Tag Helper - 自动适配开发/生产 -->
    <link rel="stylesheet" vite-href="~/main.js" />
    <script type="module" vite-src="~/main.js" asp-append-version="true"></script>
</head>
<body>
    <!-- ... 页面内容 ... -->
</body>
</html>

5. vite.config.js - Vite 配置

import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
  root: path.resolve(__dirname, 'ClientApp'),
  base: '/',  // ✅ 开发模式使用根路径
  
  build: {
    outDir: path.resolve(__dirname, 'wwwroot/dist'),
    emptyOutDir: true,
    manifest: '.vite/manifest.json',  // ✅ 生成 manifest
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'ClientApp/main.js')
      }
    }
  },
  
  server: {
    port: 5173,
    strictPort: true,
    origin: 'http://localhost:5173'
  }
});

🎯 Tag Helper 使用指南

引入脚本

<script type="module" vite-src="~/main.js"></script>

开发模式渲染:

<script type="module" src="http://localhost:5173/@vite/client"></script>
<script type="module" src="http://localhost:5173/main.js"></script>

生产模式渲染:

<script type="module" src="/dist/assets/main-abc123.js?v=..."></script>

引入样式

<link rel="stylesheet" vite-href="~/main.js" />

开发模式: 自动移除(Vite 在客户端注入样式) 生产模式:

<link rel="stylesheet" href="/dist/assets/main-abc123.css" />

同时引入脚本和样式(推荐)

<link rel="stylesheet" vite-href="~/main.js" />
<script type="module" vite-src="~/main.js" asp-append-version="true"></script>

📊 环境对比

特性开发环境生产环境
资源来源Vite Dev Serverwwwroot/dist/
Vite Server自动启动禁用
HMR✅ 完整支持❌ 禁用
Manifest不读取读取
文件哈希
适用场景本地开发正式部署

🧪 功能演示

首页包含三个演示:

  1. Alpine.js 计数器 - 使用 Alpine.js 的响应式数据
  2. Todo List - 添加、删除待办事项
  3. 技术栈介绍 - 使用 Basecoat 组件展示

🌐 部署

Docker

创建 Dockerfile

FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY ["ViteMvcApp/ViteMvcApp.csproj", "ViteMvcApp/"]
RUN dotnet restore "ViteMvcApp/ViteMvcApp.csproj"

# 安装 Node.js 并构建前端
RUN apt-get update && apt-get install -y curl
RUN curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -
RUN apt-get install -y nodejs

COPY . .
WORKDIR "/src/ViteMvcApp"
RUN npm install
RUN npm run build

RUN dotnet build "ViteMvcApp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "ViteMvcApp.csproj" -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ViteMvcApp.dll"]

IIS/Windows Server

  1. 发布应用:dotnet publish -c Release
  2. 将发布目录部署到 IIS
  3. 确保已安装 .NET 10.0 托管包

🛠️ 故障排除

Vite Dev Server 未自动启动

检查:

  1. appsettings.json"AutoRun": true
  2. 已运行 npm install
  3. 查看应用日志中的 Vite 相关输出

开发模式资源 404

检查:

  1. Vite Dev Server 是否运行在 http://localhost:5173
  2. UseViteDevelopmentServer(true) 是否正确配置
  3. Tag Helper 是否正确使用 vite-src/vite-href

生产模式资源 404

检查:

  1. 已运行 npm run build
  2. wwwroot/dist/.vite/manifest.json 存在
  3. Tag Helper 已正确使用

Alpine.js 组件不工作

检查:

  1. main.js 中正确初始化 Alpine
  2. 浏览器控制台无错误

💡 开发指南

添加新的 Alpine 组件

在视图中:

<div x-data="{ open: false }">
  <button @@click="open = !open">Toggle</button>
  <div x-show="open">Hello!</div>
</div>

自定义 Tailwind 主题

编辑 ClientApp/styles.css

@import "tailwindcss";
@import "basecoat-css";

@theme {
  --color-primary: #3b82f6;
  --color-secondary: #64748b;
}

添加新的入口点

  1. vite.config.js 中添加:
rollupOptions: {
  input: {
    main: path.resolve(__dirname, 'ClientApp/main.js'),
    admin: path.resolve(__dirname, 'ClientApp/admin.js')
  }
}
  1. 在视图中使用:
<script type="module" vite-src="~/admin.js"></script>

📜 运行日志示例

开发模式启动日志

info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5246
info: Vite.AspNetCore.ViteDevServerLauncher[21]
      Starting the Vite development server...
info: Vite.AspNetCore.ViteDevServerLauncher[22]
      Vite development server started with process ID 32420.
info: Vite.AspNetCore.ViteDevServerLauncher[26]
      The Vite development server is running at http://localhost:5173
info: Vite.AspNetCore.ViteDevHmrProxy[30]
      Establishing HMR WebSocket proxy: http://localhost:5246/?token=... -> ws://localhost:5173/



相关评论
发表
暂无相关评论...
{{item.userName}} {{item.dateDescription}}
{{item.likeCount}} 回复
{{item.content}}
{{child.userName}}@{{child.atUserName}} {{child.content}}
{{child.dateDescription}}
{{child.likeCount}} 回复