您好,登錄后才能下訂單哦!
這篇文章主要介紹“Vue服務端如何渲染SSR”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Vue服務端如何渲染SSR”文章能幫助大家解決問題。
概念:放在瀏覽器進行就是瀏覽器渲染,放在服務器進行就是服務器渲染。
客戶端渲染不利于 SEO 搜索引擎優化
服務端渲染是可以被爬蟲抓取到的,客戶端異步渲染是很難被爬蟲抓取到的
SSR直接將HTML字符串傳遞給瀏覽器。大大加快了首屏加載時間。
SSR占用更多的CPU和內存資源
一些常用的瀏覽器API可能無法正常使用
在vue中只支持beforeCreate和created兩個生命周期
yarn add vue-server-renderer vue yarn add koa koa-router
createRenderer,創建一個渲染函數 renderToString, 渲染出一個字符串
const Vue = require('vue'); const render = require('vue-server-renderer'); const Koa = require('koa'); const Router = require('koa-router'); const app = new Koa(); const router = new Router(); const vm = new Vue({ data(){ return {msg:"hello world"} }, template:`<div>{{msg}}</div>` }); router.get('/',async (ctx)=>{ let r = await render.createRenderer().renderToString(vm); ctx.body = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> ${r} </body> </html> ` }); app.use(router.routes()); app.listen(4000);
<!DOCTYPE html> <html lang="en"> <head><title>Hello</title></head> <body> <!--vue-ssr-outlet--> </body> </html>
傳入template 替換掉注釋標簽
const Vue = require('vue'); const render = require('vue-server-renderer'); const Koa = require('koa'); const Router = require('koa-router'); const app = new Koa(); const router = new Router(); const vm = new Vue({ data(){ return {msg:"hello world"} }, template:`<div>{{msg}}</div>` }); const template = require('fs').readFileSync('./index.html','utf8'); router.get('/',async (ctx)=>{ let r = await render.createRenderer({ template }).renderToString(vm); ctx.body = r; }); app.use(router.routes()); app.listen(4000);
├── config │ ├── webpack.base.js │ ├── webpack.client.js │ └── webpack.server.js ├── dist │ ├── client.bundle.js │ ├── index.html │ ├── index.ssr.html │ ├── server.bundle.js │ ├── vue-ssr-client-manifest.json │ └── vue-ssr-server-bundle.json ├── package.json ├── public │ ├── index.html │ └── index.ssr.html ├── server.js ├── src │ ├── App.vue │ ├── components │ │ ├── Bar.vue │ │ └── Foo.vue │ ├── entry-client.js │ ├── entry-server.js │ ├── app.js │ ├── router.js │ └── store.js ├── webpack.config.js
安裝插件
yarn add webpack webpack-cli webpack-dev-server vue-loader vue-style-loader css-loader html-webpack-plugin @babel/core @babel/preset-env babel-loader vue-template-compiler webpack-merge
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const VueLoaderPlugin = require('vue-loader/lib/plugin') const resolve = (dir)=>{ return path.resolve(__dirname,dir) } module.exports = { entry: resolve('./src/client-entry.js'), output:{ filename:'[name].bundle.js', path:resolve('dist') }, module:{ rules:[ { test:/.css$/, use:['vue-style-loader','css-loader'] }, { test:/.js$/, use:{ loader:'babel-loader', options:{ presets:['@babel/preset-env'] } }, exclude:/node_modules/ }, { test:/.vue$/, use:'vue-loader' } ] }, plugins:[ new VueLoaderPlugin(), new HtmlWebpackPlugin({ template:'./index.html' }) ] }
import Vue from "vue"; import App from "./App.vue"; export default () => { // 為了保證實例的唯一性所以導出一個創建實例的函數 const app = new Vue({ render: h => h(App) }); return { app }; };
import createApp from "./app"; const { app } = createApp(); app.$mount("#app"); // 客戶端渲染手動掛載到dom元素上
import createApp from "./app"; export default () => { const { app } = createApp(); return app; // 服務端渲染只需將渲染的實例導出即可 };
webpack.base.js
let path = require('path'); let VueLoaderPlugin = require('vue-loader/lib/plugin') module.exports = { output:{ filename:'[name].bundle.js', path:path.resolve(__dirname,'../dist') }, module:{ rules:[ {test:/.css/,use:['vue-style-loader','css-loader']}, { test:/.js/, use:{ loader:'babel-loader', options:{ presets:['@babel/preset-env'] }, }, exclude:/node_modules/, }, {test:/.vue/,use:'vue-loader'} ] }, plugins:[ new VueLoaderPlugin() ] }
webpack.client.js
const merge = require("webpack-merge"); const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const base = require("./webpack.base"); const resolve = filepath => { return path.resolve(__dirname, filepath); }; module.exports = merge(base, { entry: { client: resolve("../src/client-entry.js") }, plugins: [ new HtmlWebpackPlugin({ template: resolve("../template/index.client.html") }) ] });
webpack.server.js
const merge = require("webpack-merge"); const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const base = require("./webpack.base"); const resolve = filepath => { return path.resolve(__dirname, filepath); }; module.exports = merge(base, { entry: { server: resolve("../src/server-entry.js") }, target: "node", output: { libraryTarget: "commonjs2" // 導出供服務端渲染來使用 }, plugins: [ new HtmlWebpackPlugin({ filename: "index.ssr.html", template: resolve("../template/index.ssr.html"), excludeChunks: ["server"] }) ] });
"scripts": { "client:dev": "webpack-dev-server --config ./build/webpack.client.js", // 客戶端開發環境 "client:build": "webpack --config ./build/webpack.client.js", // 客戶端打包環境 "server:build": "webpack --config ./build/webpack.server.js" // 服務端打包環境 },
在App.vue上增加id="app"可以保證元素被正常激活
const Koa = require("koa"); const Router = require("koa-router"); const static = require("koa-static"); const path = require("path"); const app = new Koa(); const router = new Router(); const VueServerRenderer = require("vue-server-renderer"); const fs = require("fs"); // 服務端打包的結果 const serverBundle = fs.readFileSync("./dist/server.bundle.js", "utf8"); const template = fs.readFileSync("./dist/index.ssr.html", "utf8"); const render = VueServerRenderer.createBundleRenderer(serverBundle, { template }); router.get("/", async ctx => { ctx.body = await new Promise((resolve, reject) => { render.renderToString((err, html) => { // 必須寫成回調函數的方式否則樣式不生效 resolve(html); }); }); }); app.use(router.routes()); app.use(static(path.resolve(__dirname, "dist"))); app.listen(3000);
在index.ssr.html中需要手動引入客戶端打包后的結果
實現熱更新,自動增加preload和prefetch,以及可以使用sourceMap
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin'); // 在客戶端打包時增加插件 const VueSSRServerPlugin = require('vue-server-renderer/server-plugin'); // 在服務端打包時增加插件 const Koa = require("koa"); const Router = require("koa-router"); const static = require("koa-static"); const path = require("path"); const app = new Koa(); const router = new Router(); const VueServerRenderer = require("vue-server-renderer"); const fs = require("fs"); // 服務端打包的結果 // const serverBundle = fs.readFileSync("./dist/server.bundle.js", "utf8"); const template = fs.readFileSync("./dist/index.ssr.html", "utf8"); const serverBundle = require("./dist/vue-ssr-server-bundle.json"); const clientManifest = require("./dist/vue-ssr-client-manifest.json"); const render = VueServerRenderer.createBundleRenderer(serverBundle, { template, clientManifest // 自動注入客戶端打包后的文件 }); router.get("/", async ctx => { ctx.body = await new Promise((resolve, reject) => { render.renderToString((err, html) => { // 必須寫成回調函數的方式否則樣式不生效 resolve(html); }); }); }); app.use(router.routes()); app.use(static(path.resolve(__dirname, "dist"))); app.listen(3000);
yarn add vue-router
import Vue from "vue"; import VueRouter from "vue-router"; import Foo from "./components/Foo.vue"; Vue.use(VueRouter); export default () => { const router = new VueRouter({ mode: "history", routes: [ { path: "/", component: Foo }, { path: "/bar", component: () => import("./components/Bar.vue") } ] }); return router; };
導出路由配置
import Vue from "vue"; import App from "./App.vue"; import createRouter from "./router"; export default () => { const router = createRouter(); const app = new Vue({ router, render: h => h(App) }); return { app, router }; };
<template> <div id="app"> <router-link to="/"> foo</router-link> <router-link to="/bar"> bar</router-link> <router-view></router-view> </div> </template>
router.get("*", async ctx => { ctx.body = await new Promise((resolve, reject) => { render.renderToString({ url: ctx.url }, (err, html) => { // 必須寫成回調函數的方式否則樣式不生效 resolve(html); }); }); });
export default ({ url }) => { return new Promise((resolve, reject) => { const { app, router } = createApp(); router.push(url); router.onReady(() => { const matchComponents = router.getMatchedComponents(); if (!matchComponents.length) { return reject({ code: 404 }); } resolve(app); }, reject); }); }; // 服務器可以監控到錯誤信息,返回404 render.renderToString({ url: ctx.url }, (err, html) => { // 必須寫成回調函數的方式否則樣式不生效 if (err && err.code == 404) { resolve("404 Not Found"); } resolve(html); });
yarn add vuex
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default ()=>{ let store = new Vuex.Store({ state:{ username:'song' }, mutations:{ changeName(state){ state.username = 'hello'; } }, actions:{ changeName({commit}){ return new Promise((resolve,reject)=>{ setTimeout(() => { commit('changeName'); resolve(); }, 1000); }) } } }); return store }
// 引用vuex import createRouter from './router'; import createStore from './store' export default ()=>{ let router = createRouter(); let store = createStore(); let app = new Vue({ router, store, render:(h)=>h(App) }) return {app,router,store} }
import createApp from './main'; export default (context)=>{ return new Promise((resolve)=>{ let {app,router,store} = createApp(); router.push(context.url); // 默認訪問到/a就跳轉到/a router.onReady(()=>{ let matchComponents = router.getMatchedComponents(); // 獲取路由匹配到的組件 Promise.all(matchComponents.map(component=>{ if(component.asyncData){ return component.asyncData(store); } })).then(()=>{ context.state = store.state; // 將store掛載在window.__INITIAL_STATE__ resolve(app); }); }) }) }
// 在瀏覽器運行代碼 if(typeof window !== 'undefined' && window.__INITIAL_STATE__){ store.replaceState(window.__INITIAL_STATE__); }
export default { mounted() { return this.$store.dispatch("changeName"); }, asyncData(store) { return store.dispatch("changeName"); } };
關于“Vue服務端如何渲染SSR”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。