场景:老项目需要后端引擎将数据写入模版引擎
归档.zip
由于还是比较擅长 node ,所以还是起一个 node 服务
创建一个 node 服务
yarn add express
server.js
const express = require("express");const app = express();app.set("view engine", "pug");app.get("/", (req, res) => {res.render("index", {title: "标题",message: "hello node",});});app.listen(4000);
/views/index.pug
htmlheadtitle= titlebodyh1= messagediv(id="app")script(src="http://localhost:3000/@vite/client" type="module") // 引入前端服务文件script(src="http://localhost:3000/src/main.js" type="module") // 引入前端服务文件

正常如果需要做这种需求,一般会把我们前端代码,放到后端服务中,然后在后端服务中做静态资源映射,映射到前端目录下
打包前端项目引入到后端服务
打包前端
修改 vite.config.js
export default defineConfig({plugins: [vue(), vueJsx()],resolve: {alias: {'@': '/src','@styles': '/src/styles',},},server: {host: '0.0.0.0',},build: {manifest: true,},})
打包的 dist 会多一个
manifest.json文件{"index.html": {"file": "assets/index.af984f6b.js","src": "index.html","isEntry": true,"imports": ["_vendor.534f743d.js"],"css": ["assets/index.14ec4049.css"],"assets": ["assets/logo.03d6d6da.png"]},"_vendor.534f743d.js": {"file": "assets/vendor.534f743d.js"}}
引入到后端
把打包项目拷贝到后端服务中*
- 修改node服务
server.js
const express = require("express");const app = express();const mainfest = require("./dist/manifest.json");app.set("view engine", "pug");app.use(express.static("dist")); // 静态资源映射app.get("/", (req, res) => {res.render("index", {title: "标题",message: "hello node",index: mainfest["index.html"].file,vendor: mainfest["index.html"].imports,css: mainfest["index.html"].css[0],});});app.listen(4000);
- 通过
manifest.json文件,把前端资源引入模版中
index.pug
htmlheadtitle= titlelink(href=css rel="stylesheet" type="text/css")bodyh1= messagediv(id="app")script(src=vendor)script(src=index)


