前言
我司之前部分H5为了追求极致的首屏渲染速度,使用Next.js去开发SSR项目。
去年对我司技术栈升级到Vue3之后,萌生了对SSR项目升级到Nuxt3的想法,奈何当时Nuxt3还不稳定,不建议在生产环境使用。于是打算自己搭个Vue3 SSR服务出来。
长话短说,直接开干
一、初始化项目
npm create vite vue3-ssr -- --template vue-ts
二、修改客户端入口
1.修改~/src/main.ts
import { createSSRApp } from 'vue'
import App from './App.vue'
// 因为每次请求都会到达服务器,为了数据不会被相互污染,
// 每次请求我们都需要使用工厂函数创建新的实例,每次都返回全新的vue, router, store等
export const createApp = () => {
const app = createSSRApp(App)
return { app }
}
2.新建~/src/entry-client.ts
import { createApp } from './main'
const { app } = createApp()
app.mount("#app")
3.修改~/index.html的入口
<!DOCTYPE html>
<html lang="en">
...
<script type="module" src="/src/entry-client.ts"></script>
...
</html>
上述文件修改完,你会发现仅仅是把main.ts文件拆分出了一个客户端入口文件。其他什么都没改变。所以可直接运行npm run dev
工程就可以运行起来了。~/src/entry-client.ts
文件只是替换了main.ts
作为项目的入口。
三、创建开发服务器
使用Koa2
1.安装Koa
npm i koa && npm i @types/koa -D
2.新建~/server.js
const Koa = require('koa')
;(async () => {
const app = new Koa()
app.use(async (ctx) => {
ctx.body = `<!DOCTYPE html>
<html lang="en">
<head><title>vue3 SSR</title></head>
<body>
<h1>vue3 SSR</h1>
</body>
</html>`;
});
const port = 3000
app.listen(port, () => {
console.log(`server is listening in ${port}`)
});
})();
3.运行node server.js
4.结果:
四、渲染替换成项目根目录下的index.html
1.修改server.js服务返回的是Index.html
const fs = require('fs')
const path = require('path')
const Koa = require('koa')
;(async () => {
const app = new Koa()
// 获取 index.html
const template = fs.readFileSync(path.resolve(__dirname, 'index.html'), 'utf-8')
app.use(async (ctx) => {
ctx.body = template
})
const port = 3000
app.listen(port, () => {
console.log(`server is listening in ${port}`)
});
})();