背景:當前項目首頁和登陸后的平台在一個項目里,路由采用hash模式,現在要做SEO優化,這時候同構SSR(Server Side Rendering)服務端渲染代價顯然太大,影響范圍比較廣,同樣更改當前項目路由為history模式采用預渲染(Prerending)代價也不小。最終決定將首頁單獨出一個項目采用預渲染,然后用nginx代理來實現兩個項目之間的跳轉。
同構SSR服務端渲染這里就不多贅述了,說一下預渲染:
一、什么情況下用預渲染比較好
官方文檔建議:如果你調研服務器端渲染(SSR)只是用來改善少數營銷頁面(例如 /
, /about
, /contact
等)的 SEO,那么你可能需要預渲染。無需使用 web 服務器實時動態編譯 HTML,而是使用預渲染方式,在構建時(build time)簡單地生成針對特定路由的靜態 HTML 文件。優點是設置預渲染更簡單,並可以將你的前端作為一個完全靜態的站點。
二、選用插件
官方文檔建議:如果你使用 webpack,你可以使用 prerender-spa-plugin 輕松地添加預渲染。它已經被 Vue 應用程序廣泛測試 - 事實上,作者是 Vue 核心團隊的成員。
結合vue-meta-info這一類動態設置meta信息的插件,可以達到更好的效果。
三、插件的使用
安裝
# Yarn $ yarn add prerender-spa-plugin # or NPM $ npm i prerender-spa-plugin
vue-cli3 webpack配置
在vue.config.js中:
const PrerenderSPAPlugin = require('prerender-spa-plugin') const Renderer = PrerenderSPAPlugin.PuppeteerRenderer module.exports = { configureWebpack: { module: {}, plugins: process.env.NODE_ENV === 'production' ? [ new PrerenderSPAPlugin({ staticDir: path.join(__dirname, process.env.VUE_APP_OUTPUT_DIR), // 需要進行預渲染的路由路徑 routes: ['/', '/about'], // html文件壓縮 minify: { minifyCSS: true, // css壓縮 removeComments: true // 移除注釋 }, renderer: new Renderer({ // Optional - The name of the property to add to the window object with the contents of `inject`. injectProperty: '__PRERENDER_INJECTED', // Optional - Any values you'd like your app to have access to via `window.injectProperty`. inject: {}, // 在 main.js 中 new Vue({ mounted () {document.dispatchEvent(new Event('render-event'))}}),兩者的事件名稱要對應上。 renderAfterDocumentEvent: 'render-event' }) }) ] : [] } }
這里只在 process.env.NODE_ENV === 'production'的時候進行預渲染,輸入目錄為 process.env.VUE_APP_OUTPUT_DIR,是在.env .env.prod .env.test等全局環境變量中配置的,可以根據不同環境打包,如.env.prod的配置為:
NODE_ENV = production VUE_APP_OUTPUT_DIR = 'dist-prod' VUE_APP_PROJECT_URL = '/platform'
這里的VUE_APP_PROJECT_URL稍后再做解釋。
以上的new PrerenderSPAPlugin({})配置中刪除了
headless: false // Display the browser window when rendering. Useful for debugging.
目的是為了不打開chromium瀏覽器。
在main.js中配置:
new Vue({ router, store, render: h => h(App), mounted () { document.dispatchEvent(new Event('render-event')) // 預渲染 } }).$mount("#app")
vue-meta-info安裝使用:
安裝
# Yarn $ yarn add vue-meta-info # or NPM $ npm install vue-meta-info --save
使用
import Vue from 'vue' import MetaInfo from 'vue-meta-info' Vue.use(MetaInfo) <template> ... </template> <script> export default { metaInfo: { title: 'My Example App', // set a title meta: [{ // set meta name: 'keyWords', content: 'My Example App' }] link: [{ // set link rel: 'asstes', href: 'https://assets-cdn.github.com/' }] } } </script>
如果你的title或者meta是異步加載的,那么你可能需要這樣使用
<template> ... </template> <script> export default { name: 'async', metaInfo () { return { title: this.pageName } }, data () { return { pageName: 'loading' } }, mounted () { setTimeout(() => { this.pageName = 'async' }, 2000) } } </script>
三、項目間跳轉配置
現在說一下VUE_APP_PROJECT_URL這個變量,這個變量便是兩個項目間跳轉的關鍵。在本地開發中,可以通過設置.env中的變量:
VUE_APP_PROJECT_URL = 'http://localhost:8080'
另一個項目
VUE_APP_PROJECT_URL = 'http://localhost:8081'
然后通過window.location.href的方式進行兩個本地項目之間的跳轉:
export function toUrl (query) { // 動態更改href window.location.href = process.env.VUE_APP_PROJECT_URL + query }
至於線上怎么進行跳轉,可以這么配置.env.prod中的變量:
VUE_APP_PROJECT_URL = '/'
另一個項目
VUE_APP_PROJECT_URL = '/platform'
然后在nginx中配置:
### 默認進入的項目 ### server { listen 30002; server_name xxx.xx.xxx.xxx; proxy_buffer_size 8k; proxy_buffers 8 32k; set $root /var/www/page-for-seo/dist-prod; root $root; index index.html index.htm index.php; error_log /var/nginx/logs/error.log error; access_log /var/nginx/logs/access.log; #access_log off; ### 客戶端請求錯誤處理 ### error_page 403 404 /404.html; location = /404.html { return 404 'Sorry, File not Found!'; } ### 服務端請求錯誤處理 ### error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } ### 靜態資源有效期 ### location ~ .*\.(jpeg|png|jpg|gif)$ { expires 1d; } ### 匹配所有請求 ### location / { try_files $uri $uri/ /index.php?$query_string; } ### 匹配 platform/ 然后進行代理 ### location ^~ /platform/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://xxx.xx.xxx.xxx:30012/; } } ### 要進行跳轉的項目 ### server { listen 30012; server_name xxx.xx.xxx.xxx; proxy_buffer_size 8k; proxy_buffers 8 32k; set $root /var/www/platform/dist-prod; root $root; index index.html index.htm index.php; error_log /var/nginx/logs/error.log error; access_log /var/nginx/logs/access.log; #access_log off; ### 客戶端請求錯誤處理 ### error_page 403 404 /404.html; location = /404.html { return 404 'Sorry, File not Found!'; } ### 服務端請求錯誤處理 ### error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } ### 靜態資源有效期 ### location ~ .*\.(jpeg|png|jpg|gif)$ { expires 1d; } ### 匹配所有請求 ### location / { try_files $uri $uri/ /index.php?$query_string; } }