記錄 rendertron 實(shí)戰(zhàn) Vue SPA單頁面應(yīng)用解決SEO問題

具體參考官方文檔 https://github.com/GoogleChrome/rendertron

安裝

全局安裝

npm install -g rendertron

項(xiàng)目安裝

// 使用 express 作為服務(wù)端框架,配合官方提供的 rendertron-middleware中間件,開箱即用
// vue history 路由兼容中間件 connect-history-api-fallback 
npm i  express rendertron-middleware  connect-history-api-fallback

服務(wù)端代碼


// 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 = [
];

// 注冊中間件  默認(rèn)是 /index.html
app.use(history());

app.use(rendertron.makeMiddleware({
    proxyUrl: 'http://localhost:3000/render', // 默認(rèn)rendertron是3000端口
    userAgentPattern: new RegExp(spiderUserAgents.join('|'), 'i')
}));

// spa項(xiàng)目打包完成的目錄
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 構(gòu)建的項(xiàng)目放在 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"
  }

控制臺運(yùn)行

rendertron
image
npm run buid
npm run start

通過postman 測試得到渲染完成后的dom節(jié)點(diǎn)

image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。