const fs = require("fs"); const Koa = require("koa"); const path = require("path"); const koaStatic = require('koa-static') const app = new Koa(); const resolve = file => path.resolve(__dirname, file); // 开放dist目录 app.use(koaStatic(resolve('./dist'))) // 第 2 步:获得一个createBundleRenderer const { createBundleRenderer } = require("vue-server-renderer"); const bundle = require("./dist/vue-ssr-server-bundle.json"); const clientManifest = require("./dist/vue-ssr-client-manifest.json"); const renderer = createBundleRenderer(bundle, { runInNewContext: false, template: fs.readFileSync(resolve("./src/index.temp.html"), "utf-8"), clientManifest: clientManifest }); function renderToString(context) { return new Promise((resolve, reject) => { renderer.renderToString(context, (err, html) => { err ? reject(err) : resolve(html); }); }); } // 第 3 步:添加一个中间件来处理所有请求 app.use(async (ctx, next) => { const context = { title: "ssr test", url: ctx.url }; // 将 context 数据渲染为 HTML const html = await renderToString(context); ctx.body = html; }); const port = 3000; app.listen(port, function() { console.log(`server started at localhost:${port}`); });
3.5 运行server.js
node server.js
访问localhost:3000,可以看到页面的数据都是又服务端渲染完成后返回的。到这一步已经基本算完成了SSR的构建了。
如果有问题的话,可以把dist目录下的index.html文件删了。避免直接访问到了该html文件。
4、集成vuex
修改store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export function createStore() { return new Vuex.Store({ state: { }, mutations: { }, actions: { } }); }
修改main.js
import Vue from "vue"; import App from "./App.vue"; import { createRouter } from "@/router"; import { createStore } from "@/store"; export function createApp() { const router = createRouter(); const store = createStore() // + const app = new Vue({ router, store, // + render: h => h(App) }); return { app, router }; }
再次运行脚本构建
npm run build:win node server.js
5、案例代码
附上案例源码 https://github.com/lentoo/vue-cli-ssr-example欢迎star
6、总结
到目前为止,仅仅是完成了SSR的基础部分,还有相关的 SSR热更新之类的问题还需要继续探索。如果有好的热更新方法欢迎发出了参考参考。