首页文章关于

vite-不同场景下的集成及配置方式

vitebuild toolarchitecture

在实际业务开发中,只是通过 vite 官方提供的模版还不足以满足当前业务接入的需求。特此记录整理常见业务模型下对于 vite 的整合方式

传统后端集成

传统后端集成是将 vite 原本的开发环境能力整合到现有的后端服务中,处于前端的生产环境处理没有变动

在 vite 配置中配置入口文件并启用manifest

/frontend/xxx/vite.config.js
js
export default defineConfig({
build: {
manifest: true, // 生成manifest.json以便生产环境访问资源
rollupOptions: {
input: "/xxx/main.js", // 覆盖默认的.html入口
},
},
})

模块预加载polyfill

/frontend/xxx/main.js
js
import "vite/modulepreload-polyfill"

开发环境中,在后端 serve 的 index.html 中添加 vite 客户端文件和前端入口文件

/server/template/index.html
html
<script type="module" src="http://localhost:5183/@vite/client"></script>
<script type="module" src="http://localhost:5183/frontend/main.js"></script>

生产环境中通过生成的manifest清单文件进行对前端模版进行注入并渲染,

js
// 以node服务作为后端为例
const manifest = require("./dist/manifest.json")
// 确保前端资源目录的映射正确
app.use(express.static("dist"))
app.ge("/", (req, res) => {
res.render("index", {
title: "xxx",
index: manifest["index.html"].file,
vendor: manifest["index.html"].imports.vendor,
css: manifest["index.html"].css[0],
})
})

中间件模式

当想要对自己的 server 又完全控制权时可以使用中间件模式(任意兼容 connect 的 nodejs 框架),典型的例子就是以 node 服务端渲染

js
import express from "express"
import { createServer as createViteServer } from "vite"
async function createServer() {
const app = new express()
// 以中间件模式创建 Vite 应用,这将禁用 Vite 自身的 HTML 服务逻辑
// 并让上级服务器接管控制
const vite = await createViteServer({
server: {
middlewareMode: true,
},
appType: "custom",
})
// 使用 vite 的 Connect 实例作为中间件
// 如果你使用了自己的 express 路由(express.Router()),你应该使用 router.use
app.use(vite.middlewares)
app.use("*", async (req, res) => {
// 处理路由index.html的逻辑
})
app.listen(3000)
}
createServer()

中间层代理

todo

Copyright © 2023, Daily learning records and sharing. Build by