stats = stats.toJson();
if (stats.errors.length) {
console.error(stats.errors);
return;
}
// 生成的bundle放到appSSR模块,应用程序可以直接读取
bundle = JSON.parse(mfs.readFileSync(path.resolve(cwd,'./dist/vue-ssr-server-bundle.json'), 'utf-8'));
appSSR.bundle = bundle;
});
}
渲染中间件配置
产品环境下,打包后的客户端和服务端的
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');










