深入淺出通過vue-cli3構建一個SSR應用程序【實踐】


深入淺出通過vue-cli3構建一個SSR應用程序【實踐】


轉發鏈接:https://www.jianshu.com/p/bb07d77b91f7

1、前沿

1.1、什麼是SSR

SSR(服務端渲染)顧名思義就是將頁面在服務端渲染完成後在客戶端直接展示。

1.2、客戶端渲染與服務端渲染的區別

傳統的SPA模式

即客戶端渲染的模式

  1. Vue.js構建的應用程序,默認情況下是有一個html模板頁,然後通過webpack打包生成一堆js、css等等資源文件。然後塞到index.html中
  2. 用戶輸入url訪問頁面 -> 先得到一個html模板頁 -> 然後通過異步請求服務端數據 -> 得到服務端的數據 -> 渲染成局部頁面 -> 用戶

SSR模式

即服務端渲染模式

  1. 用戶輸入url訪問頁面 -> 服務端接收到請求 -> 將對應請求的數據渲染完一個網頁 -> 返回給用戶

1.3、為什麼要使用SSR呢?

ssr的好處官網已經給出,最有意思的兩個優點如下:

  1. 更有好的SEO。由於搜索引擎爬蟲抓取工具可以直接查看完全渲染的頁面。
  2. 更快的內容到達時間(time-to-content)

1.4、SSR原理

這是vue.js官方的SSR原理介紹圖,從這張圖片,我們可以知道:我們需要通過Webpack打包生成兩份bundle文件:

  • Client Bundle,給瀏覽器用。和純Vue前端項目Bundle類似
  • Server Bundle,供服務端SSR使用,一個json文件

不管你項目先前是什麼樣子,是否是使用vue-cli生成的。都會有這個構建改造過程。在構建改造這裡會用到 vue-server-renderer 庫,這裡要注意的是 vue-server-renderer 版本要與Vue版本一樣。

深入淺出通過vue-cli3構建一個SSR應用程序【實踐】

image

2、開始構建基於vue-cli3 的SSR應用程序

瞭解ssr原理後,來開始step by step搭建一個自己的SSR應用程序

  1. 安裝vue-cli3

全局安裝vue-cli腳手架

<code>npm install @vue/cli -g --registry=https://registry.npm.taobao.org
/<code>
  1. 創建一個vue項目
<code>vue create ssr-example 
/<code>

會進入到一個交互bash界面,按自己需要選擇

深入淺出通過vue-cli3構建一個SSR應用程序【實踐】

image

一步一步回車,根據自己需要選擇

  1. 運行項目
<code>npm run serve
/<code>
深入淺出通過vue-cli3構建一個SSR應用程序【實踐】

image

看到這個提示,說明成功了一半了,接下來進行後一半的改造。

3、進行SSR改造

3.1 安裝需要的包

  1. 安裝 vue-server-renderer
  2. 安裝 lodash.merge
  3. 安裝 webpack-node-externals
  4. 安裝 cross-env
<code>npm install vue-server-renderer lodash.merge webpack-node-externals cross-env --registry=https://registry.npm.taobao.org --save-dev
/<code>

3.2 在服務器中集成

  1. 在項目根目錄下新建一個server.js
  2. 安裝koa2
<code>npm install koa koa-static --save --registry=https://registry.npm.taobao.org
/<code>
  1. 在koa2集成ssr
<code>// server.js
// 第 1 步:創建一個 Vue 實例
const Vue = require("vue");

const Koa = require("koa");
const app = new Koa();
// 第 2 步:創建一個 renderer
const renderer = require("vue-server-renderer").createRenderer();


// 第 3 步:添加一箇中間件來處理所有請求

app.use(async (ctx, next) => {
const vm = new Vue({
data: {
title: "ssr example",
url: ctx.url
},
template: `
訪問的 URL 是: {{ url }}
`
});
// 將 Vue 實例渲染為 HTML
renderer.renderToString(vm, (err, html) => {
if(err){
ctx.res.status(500).end('Internal Server Error')
return
}
ctx.body = html
});
});

const port = 3000;
app.listen(port, function() {
console.log(`server started at localhost:${port}`);
});
/<code>
  1. 運行server.js
<code>node server.js
/<code>
深入淺出通過vue-cli3構建一個SSR應用程序【實踐】

image

看到這個說明一個簡單的ssr構建成功了。

不過到目前為止,我們並沒有將客戶端的.vue文件通過服務端進行渲染,那麼如何將前端的.vue文件與後端node進行結合呢?

3.3 改造前端配置,以支持SSR

1、修改源碼結構

  • 在src目錄下新建兩個文件,一個entry-client.js 僅運行於瀏覽器 一個entry-server.js 僅運行於服務器
  • 修改main.js

main.js 是我們應用程序的「通用 entry」。在純客戶端應用程序中,我們將在此文件中創建根 Vue 實例,並直接掛載到 DOM。但是,對於服務器端渲染(SSR),責任轉移到純客戶端 entry 文件。app.js 簡單地使用 export 導出一個 createApp 函數:

<code>// main.js
import Vue from 'vue'
import App from './App.vue'
import { createRouter } from "./router";

// 導出一個工廠函數,用於創建新的

// 應用程序、router 和 store 實例
export function createApp () {
const router = createRouter();
const app = new Vue({
router,
// 根實例簡單的渲染應用程序組件。
render: h => h(App)
})
return { app,router }
}
/<code>
  • 修改entry-client.js

客戶端 entry 只需創建應用程序,並且將其掛載到 DOM 中

<code>import { createApp } from './main'

// 客戶端特定引導邏輯……
const { app } = createApp()

// 這裡假定 App.vue 模板中根元素具有 `id="app"`
app.$mount('#app')
/<code>
  • 修改entry-server.js

服務器 entry 使用 default export 導出函數,並在每次渲染中重複調用此函數。

<code>import { createApp } from "./main";

export default context => {
// 因為有可能會是異步路由鉤子函數或組件,所以我們將返回一個 Promise,
// 以便服務器能夠等待所有的內容在渲染前,

// 就已經準備就緒。
return new Promise((resolve, reject) => {
const { app, router } = createApp();

// 設置服務器端 router 的位置
router.push(context.url);

// 等到 router 將可能的異步組件和鉤子函數解析完
router.onReady(() => {
const matchedComponents = router.getMatchedComponents();
// 匹配不到的路由,執行 reject 函數,並返回 404
if (!matchedComponents.length) {
return reject({
code: 404
});
}
// Promise 應該 resolve 應用程序實例,以便它可以渲染
resolve(app);
}, reject);
});
};
/<code>
  • 修改router.js
<code>import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'

Vue.use(Router)

export function createRouter(){
return new Router({
mode: 'history', //一定要是history模式
routes: [
{
path: '/',
name: 'home',
component: Home
},
{

path: '/about',
name: 'about',
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
}
]
})
}

/<code>

2、修改webpack配置

在vue-cli3創建的vue項目,已經沒有了之前的webpack.base.conf.js、webpack.dev.conf.js、webpack.prod.conf.js。那麼如何進行webpack的配置呢?

在vue-cli官網上也說明了如何使用。 調整 webpack 配置最簡單的方式就是在 vue.config.js 中的 configureWebpack 選項提供一個對象,該對象將會被 webpack-merge 合併入最終的 webpack 配置。

  1. 在項目根目錄下,新建一個vue.config.js
<code>// vue.config.js

const VueSSRServerPlugin = require("vue-server-renderer/server-plugin");
const VueSSRClientPlugin = require("vue-server-renderer/client-plugin");
const nodeExternals = require("webpack-node-externals");
const merge = require("lodash.merge");
const TARGET_NODE = process.env.WEBPACK_TARGET === "node";
const target = TARGET_NODE ? "server" : "client";


module.exports = {
css: {
extract: false
},
configureWebpack: () => ({
// 將 entry 指向應用程序的 server / client 文件
entry: `./src/entry-${target}.js`,
// 對 bundle renderer 提供 source map 支持
devtool: 'source-map',

target: TARGET_NODE ? "node" : "web",
node: TARGET_NODE ? undefined : false,
output: {
libraryTarget: TARGET_NODE ? "commonjs2" : undefined
},
// https://webpack.js.org/configuration/externals/#function
// https://github.com/liady/webpack-node-externals
// 外置化應用程序依賴模塊。可以使服務器構建速度更快,
// 並生成較小的 bundle 文件。
externals: TARGET_NODE
? nodeExternals({
// 不要外置化 webpack 需要處理的依賴模塊。
// 你可以在這裡添加更多的文件類型。例如,未處理 *.vue 原始文件,
// 你還應該將修改 `global`(例如 polyfill)的依賴模塊列入白名單
whitelist: [/\\.css$/]
})
: undefined,
optimization: {
splitChunks: undefined
},
plugins: [TARGET_NODE ? new VueSSRServerPlugin() : new VueSSRClientPlugin()]
}),
chainWebpack: config => {
config.module
.rule("vue")
.use("vue-loader")
.tap(options => {
merge(options, {
optimizeSSR: false
});
});
}
};
/<code>
  1. 修改package,新增三個腳本來生成bundle.json
<code>"build:client": "vue-cli-service build", 

"build:server": "cross-env WEBPACK_TARGET=node vue-cli-service build --mode server",
"build:win": "npm run build:server && move dist\\\\vue-ssr-server-bundle.json bundle && npm run build:client && move bundle dist\\\\vue-ssr-server-bundle.json",
/<code>
深入淺出通過vue-cli3構建一個SSR應用程序【實踐】

image

  1. 執行命令
<code>npm run build:win
/<code>

在dist目錄下會生成兩個json文件

深入淺出通過vue-cli3構建一個SSR應用程序【實踐】

image

3.4 改造server.js 代碼

<code>const fs = require("fs");
const Koa = require("koa");
const path = require("path");
const koaStatic = require('koa-static')
const app = new Koa();

const resolve = file => path.resolve(__dirname, file);
// 開放dist目錄
app.use(koaStatic(resolve('./dist')))

// 第 2 步:獲得一個createBundleRenderer
const { createBundleRenderer } = require("vue-server-renderer");
const bundle = require("./dist/vue-ssr-server-bundle.json");
const clientManifest = require("./dist/vue-ssr-client-manifest.json");

const renderer = createBundleRenderer(bundle, {
runInNewContext: false,
template: fs.readFileSync(resolve("./src/index.temp.html"), "utf-8"),
clientManifest: clientManifest
});

function renderToString(context) {
return new Promise((resolve, reject) => {
renderer.renderToString(context, (err, html) => {
err ? reject(err) : resolve(html);
});
});
}
// 第 3 步:添加一箇中間件來處理所有請求
app.use(async (ctx, next) => {
const context = {
title: "ssr test",
url: ctx.url
};
// 將 context 數據渲染為 HTML
const html = await renderToString(context);
ctx.body = html;
});

const port = 3000;
app.listen(port, function() {

console.log(`server started at localhost:${port}`);
});
/<code>

3.5 運行server.js

<code>node server.js
/<code>

訪問 localhost:3000,可以看到頁面的數據都是由服務端渲染完成後返回的。到這一步已經基本算完成了SSR的構建了。

如果有問題的話,可以把dist目錄下的index.html文件刪了。避免直接訪問到了該html文件。

深入淺出通過vue-cli3構建一個SSR應用程序【實踐】

image

4、集成vuex

  • 修改store.js
<code>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export function createStore() {
return new Vuex.Store({
state: {

},
mutations: {

},
actions: {

}
});
}

/<code>
  • 修改main.js
<code>import Vue from "vue";
import App from "./App.vue";
import { createRouter } from "@/router";
import { createStore } from "@/store";
export function createApp() {
const router = createRouter();
const store = createStore() // +
const app = new Vue({
router,
store, // +
render: h => h(App)
});
return { app, router,store };
}
/<code>
  • 再次運行腳本構建
<code>npm run build:win
node server.js
/<code>

5、案例代碼

附上案例源碼 https://github.com/lentoo/vue-cli-ssr-example 歡迎star

6、總結

到目前為止,僅僅是完成了SSR的基礎部分,還有如何實現開發模式下熱更新的內容,具體可以查看這篇文章:基於vue-cli3 SSR 程序實現熱更新功能

推薦Vue學習資料文章:

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》

《 》


作者:lentoo
轉發鏈接:https://www.jianshu.com/p/bb07d77b91f7


分享到:


相關文章: