大多數Vue項目要支持SSR應該是爲了SEO考慮,畢竟對於WEB應用來講,搜索引擎是一個很大的流量入口。Vue SSR如今已經比較成熟了,可是若是是把一個SPA應用改形成SSR應用,成本仍是有些高的,這工做量無異於重構前端。另外對前端的技術要求也是挺高的,須要對Vue比較熟悉,還要有Node.js 和 webpack 的應用經驗。html
Vue是一個構建客戶端應用的框架,即vue組件是在瀏覽器中進行渲染的。所謂服務端渲染,指的是把vue組件在服務器端渲染爲組裝好的HTML字符串,而後將它們直接發送到瀏覽器,最後須要將這些靜態標記"激活"爲客戶端上徹底可交互的應用程序。前端
先附上demo地址:https://github.com/wmui/vue-s...vue
第一步:編寫entry-client.js和entry-server.jsnode
entry-client.js只在瀏覽器環境下執行,因此須要顯示調用$mount方法,掛載DOM節點webpack
import Vue from 'vue'; import App from './App.vue'; import createStore from './store/index.js'; function createApp() { const store = createStore(); const app = new Vue({ store, render: h => h(App) }); return {app, store} } const { app, store } = createApp(); // 使用window.__INITIAL_STATE__中的數據替換整個state中的數據,這樣服務端渲染結束後,客戶端也能夠自由操做state中的數據 if (window.__INITIAL_STATE__) { store.replaceState(window.__INITIAL_STATE__); } app.$mount('#app');
entry-server.js須要導出一個函數,在服務端渲染期間會被調用git
import Vue from 'vue'; import App from './App.vue'; import createStore from './store/index.js'; export default function(context) { // context是上下文對象 const store = createStore(); let app = new Vue({ store, render: h => h(App) }); // 找到全部 asyncData 方法 let components = App.components; let asyncDataArr = []; // promise集合 for (let key in components) { if (!components.hasOwnProperty(key)) continue; let component = components[key]; if (component.asyncData) { asyncDataArr.push(component.asyncData({store})) // 把store傳給asyncData } } // 全部請求並行執行 return Promise.all(asyncDataArr).then(() => { // context.state 賦值成什麼,window.__INITIAL_STATE__ 就是什麼 // 這下你應該明白entry-client.js中window.__INITIAL_STATE__是哪來的了,它是在服務端渲染期間被添加進上下文的 context.state = store.state; return app; }); };
上面的asyncData是幹嗎用的?其實,這個函數是專門請求數據用的,你可能會問請求數據爲何不在beforeCreate
或者created
中完成,還要專門定義一個函數?雖然beforeCreate
和created
在服務端也會被執行(其餘周期函數只會在客戶端執行),可是咱們都知道請求是異步的,這就致使請求發出後,數據還沒返回,渲染就已經結束了,因此沒法把 Ajax 返回的數據也一併渲染出來。所以須要想個辦法,等到全部數據都返回後再渲染組件github
asyncData須要返回一個promise,這樣就能夠等到全部請求都完成後再渲染組件。下面是在foo組價中使用asyncData的示例,在這裏完成數據的請求web
export default { asyncData: function({store}) { return store.dispatch('GET_ARTICLE') // 返回promise }, computed: { article() { return this.$store.state.article } } }
第二步:配置webpackpromise
webpack配置比較簡單,可是也須要針對client和server端單獨配置瀏覽器
webpack.client.conf.js顯然是用來打包客戶端應用的
module.exports = merge(base, { entry: { client: path.join(__dirname, '../entry-client.js') } });
webpack.server.conf.js用來打包服務端應用,這裏須要指定node環境
module.exports = merge(base, { target: 'node', // 指定是node環境 entry: { server: path.join(__dirname, '../entry-server.js') }, output: { filename: '[name].js', // server.js libraryTarget: 'commonjs2' // 必須按照 commonjs規範打包才能被服務器調用。 }, plugins: [ new HtmlWebpackPlugin({ template: path.join(__dirname, '../index.ssr.html'), filename: 'index.ssr.html', files: { js: 'client.js' }, // client.js須要在html中引入 excludeChunks: ['server'] // server.js只在服務端執行,因此不能打包到html中 }) ] });
第三步:啓動服務
打包完成後就能夠啓動服務了,在start.js
中咱們須要把server.js加載進來,而後經過renderToString方法把渲染好的html返回給瀏覽器
const bundle = fs.readFileSync(path.resolve(__dirname, 'dist/server.js'), 'utf-8'); const renderer = require('vue-server-renderer').createBundleRenderer(bundle, { template: fs.readFileSync(path.resolve(__dirname, 'dist/index.ssr.html'), 'utf-8') // 服務端渲染數據 }); server.get('*', (req, res) => { renderer.renderToString((err, html) => { // console.log(html) if (err) { console.error(err); res.status(500).end('服務器內部錯誤'); return; } res.end(html); }) });
demo已經上傳到github: http://github.com/wmui/vue-ss...
我的實踐Vue SSR已有一段時間,發現要想搭建一套完整的 SSR 服務框架仍是頗有挑戰的,或許 Nuxt 是一個不錯的選擇,對 Nuxt 感興趣的朋友能夠參考個人一個開源小做品Essay
以上,感謝閱讀!