cli+express手把教你搭建SSR(6)

const serverConf = require("./webpack.server.conf"); const webpack = require("webpack"); const fs = require("fs"); const path = require("path"); // 读取内存中的.json文件 // 这个模块需要手动安装 const Mfs = require("memory-fs"); const axios = require("axios"); module.exports = (cb) => { const webpackComplier = webpack(serverConf); var mfs = new Mfs(); webpackComplier.outputFileSystem = mfs; webpackComplier.watch({},async (error,stats) => { if(error) return console.log(error); stats = stats.toJson(); stats.errors.forEach(error => console.log(error)); stats.warnings.forEach(warning => console.log(warning)); // 获取server bundle的json文件 let serverBundlePath = path.join(serverConf.output.path,'vue-ssr-server-bundle.json'); let serverBundle = JSON.parse(mfs.readFileSync(serverBundlePath,"utf-8")); // 获取client bundle的json文件 let clientBundle = await axios.get("http://localhost:/8080/vue-ssr-client-manifest.json"); // 获取模板 let template = fs.readFileSync(path.join(__dirname,".."."index.html"),"utf-8"); cb && cb(serverBundle,clientBundle,template); }) };

根目录/server.js(手动创建)

const devServer = require("./build/dev-server.js"); const express = require("express"); const app = express(); const vueRender = require("vue-server-render"); app.get('*',(request,respones) => { respones.status(200); respones.setHeader("Content-Type","text/html;charset-utf-8;"); devServer((serverBundle,clientBundle,template) => { let render = vueRender.createBundleRenderer(serverBundle,{ template, clientManifest:clientBundle.data, // 每次创建一个独立的上下文 renInNewContext:false }); render.renderToString({ url:request.url }).then((html) => { respones.end(html); }).catch(error => console.log(error)); }); }) app.listen(5000,() => { console.log("服务已启动") });

index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div> <!--vue-ssr-outlet--> </div> <!-- built files will be auto injected --> </body> </html>

以上就是所有要更改和添加的配置项,配置完所有地方就可以完成服务端渲染。此时需要在package.json中的sctipt中添加启动项:http:node server.js,就可以正常运行项目了。注意一定要去访问服务端设置的端口,同时要保证你的客户端也是在线的。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/8b6db41a529668b00d78180a807ff1c9.html