<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
概念:放在瀏覽器進行就是瀏覽器渲染,放在伺服器進行就是伺服器渲染。
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; // 伺服器端渲染只需將渲染的範例匯出即可 };
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() ] }
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") }) ] });
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範例詳解的詳細內容,更多關於Vue 伺服器端渲染SSR的資料請關注it145.com其它相關文章!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45