产品环境下,打包后的客户端和服务端的Bundle会存储为vue-ssr-client-manifest.json与vue-ssr-server-bundle.json,通过文件流模块fs读取即可,但在开发环境下,我创建了一个appSSR模块,在发生代码更改时,会触发Webpack热更新,appSSR对应的bundle也会更新,appSSR模块代码如下所示:
- let clientManifest;
- let bundle;
- const appSSR = {
- get bundle() {
- return bundle;
- },
- set bundle(val) {
- bundle = val;
- },
- get clientManifest() {
- return clientManifest;
- },
- set clientManifest(val) {
- clientManifest = val;
- }
- };
- module.exports = appSSR;
通过引入appSSR模块,在开发环境下,就可以拿到clientManifest和ssrBundle,项目的渲染中间件如下:
- const fs = require('fs');
- const path = require('path');
- const ejs = require('ejs');
- const vue = require('vue');
- const vssr = require('vue-server-renderer');
- const createBundleRenderer = vssr.createBundleRenderer;
- const dirname = process.cwd();
- const env = process.env.RUN_ENVIRONMENT;
- let bundle;
- let clientManifest;
- if (env === 'development') {
- // 开发环境下,通过appSSR模块,拿到clientManifest和ssrBundle
- let appSSR = require('./../../core/app.ssr.js');
- bundle = appSSR.bundle;
- clientManifest = appSSR.clientManifest;
- } else {
- bundle = JSON.parse(fs.readFileSync(path.resolve(__dirname, './dist/vue-ssr-server-bundle.json'), 'utf-8'));
- clientManifest = JSON.parse(fs.readFileSync(path.resolve(__dirname, './dist/vue-ssr-client-manifest.json'), 'utf-8'));
- }
- module.exports = async function(ctx) {
- ctx.status = 200;
- let html;
- let context = await ctx.getTplContext();
- ctx.logger('进入SSR,context为: ', JSON.stringify(context));
- const tpl = fs.readFileSync(path.resolve(__dirname, './newTemplate.html'), 'utf-8');
- const renderer = createBundleRenderer(bundle, {
- runInNewContext: false,
- template: tpl, // (可选)页面模板
- clientManifest: clientManifest // (可选)客户端构建 manifest
- });
- ctx.logger('createBundleRenderer renderer:', JSON.stringify(renderer));
- try {
- html = await renderer.renderToString({
- ...context,
- url: context.CTX.url,
- });
- } catch(err) {
- ctx.logger('SSR renderToString 失败: ', JSON.stringify(err));
- console.error(err);
- }
- ctx.body = html;
- };
如何对现有项目进行改造?
基本目录改造
使用Webpack来处理服务器和客户端的应用程序,大部分源码可以使用通用方式编写,可以使用Webpack支持的所有功能。
(编辑:ASP站长网)
|