将Vite开发服务器文件部署到ASP.NET项目时出现React Preamble错误
ASP.NET MVC + React + Vite 多页面应用(MPA)集成开发阶段错误排查
我正在搭建一个ASP.NET MVC应用,ClientApp采用React+Vite作为构建工具,目标是构建**多页面应用(MPA)**而非单页面应用(SPA),每个页面对应独立的.tsx文件(如home.tsx、about.tsx等)。
开发阶段要求ClientApp文件通过Vite开发服务器提供,实现热模块替换(HMR);生产阶段则使用wwwroot/dist目录下的打包产物。
已完成的配置
1. Program.cs(ASP.NET 配置)
通过Vite.AspNetCore包配置与Vite开发服务器的通信:
using Vite.AspNetCore.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services.AddViteServices(options => { options.PackageDirectory = "ClientApp"; // Set the root path to the ClientApp folder }); builder.Services.AddControllersWithViews(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } else { app.UseViteDevelopmentServer(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
2. _Layout.cshtml(视图资源加载)
在共享布局中添加开发环境下从Vite服务器加载资源的代码,根据页面动态加载对应.tsx入口:
<environment include="Development"> <script type="module" src="https://localhost:5173/@vite/client"></script> <link rel="stylesheet" href="https://localhost:5173/src/theme/site.css" /> @if (ViewData["ViteScript"] != null) { <script defer type="module" src="@($"https://localhost:5173/src/pages/{ViewData["ViteScript"]}/index.tsx")"></script> } </environment>
页面名称(如"home")通过Razor视图顶部的ViewData["ViteScript"]传递,对应ClientApp/src/pages/home/index.tsx文件。
3. vite.config.ts(Vite配置)
import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import mkcert from "vite-plugin-mkcert"; import appsettings from "../appsettings.json"; import appsettingsDev from "../appsettings.Development.json"; const cssPattern = /\.css$/; const imagePattern = /\.(png|jpe?g|gif|svg|webp|avif)$/; export default defineConfig({ plugins: [react(), mkcert()], build: { manifest: appsettings.Vite.Manifest, outDir: "../wwwroot/dist", emptyOutDir: true, rollupOptions: { input: { home: "./src/pages/home/index.tsx", site: "./src/site.ts", styles: "./src/theme/site.css", }, output: { entryFileNames: "js/[name].js", chunkFileNames: "js/[name]-chunk.js", assetFileNames: (info) => { if (info.name) { if (cssPattern.test(info.name)) { return "css/[name][extname]"; } if (imagePattern.test(info.name)) { return "images/[name][extname]"; } return "assets/[name][extname]"; } else { return "[name][extname]"; } }, }, }, }, server: { port: appsettingsDev.Vite.Server.Port, strictPort: true, hmr: { host: "localhost", clientPort: appsettingsDev.Vite.Server.Port, }, }, });
遇到的错误
启动端口5173的Vite开发服务器后运行ASP.NET应用,控制台出现以下错误:
Uncaught Error: @vitejs/plugin-react can't detect preamble. Something is wrong.
补充信息
Chrome开发者工具的Sources标签中,可看到ASP.NET应用运行在localhost:44380,Vite开发服务器运行在localhost:5173,且能正常看到ExampleComponent.tsx、pages/home/index.tsx等文件,但上述错误导致React组件无法正常加载。
寻求有类似MPA集成Vite开发服务器经验的开发者提供解决方案,感谢!
内容的提问来源于stack exchange,提问作者Alan N
相关产品推荐
相关产品推荐

