安裝
全局安裝
npm install -g rendertron
項目安裝
// 使用 express 作為服務端框架,配合官方提供的 rendertron-middleware中間件仔拟,開箱即用
// vue history 路由兼容中間件 connect-history-api-fallback
npm i express rendertron-middleware connect-history-api-fallback
服務端代碼
// server/index.js
const express = require('express');
// rendertron express 官方中間件
const rendertron = require('rendertron-middleware');
const app = express();
// history 路由兼容中間件
const history = require('connect-history-api-fallback');
let port = process.env.PORT || 8080;
// 自定義 user-agent 不知道為啥掘金不讓發(fā)观游,具體的列表自己去找吧
const spiderUserAgents = [
];
// 注冊中間件 默認是 /index.html
app.use(history());
app.use(rendertron.makeMiddleware({
proxyUrl: 'http://localhost:3000/render', // 默認rendertron是3000端口
userAgentPattern: new RegExp(spiderUserAgents.join('|'), 'i')
}));
// spa項目打包完成的目錄
app.use(express.static('dist'));
app.listen(port, function () {
console.log('http://127.0.0.1:' + port);
console.log('listening to ' + port);
});
網(wǎng)站根目錄下面配置config.json
vue cli3 構建的項目放在 public 下面
config.json
{
"cache": "memory",
"cacheConfig": {
"cacheDurationMinutes": 120,
"cacheMaxEntries": 50
}
}
package.json
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"start": "node server/index.js",
"lint": "vue-cli-service lint"
}
控制臺運行
rendertron
image
npm run buid
npm run start
通過postman 測試得到渲染完成后的dom節(jié)點
image