Vue SSR
Use Vue 2.0 server-side rendering with Express
Installation
npm i vue-ssr --save
Usage
const express = const router = express const VueSSR = // webpack server-side bundle configconst serverConfig = // create a project rendererconst indexRenderer = projectName: 'index' rendererOptions: cache: max: 1000 maxAge: 1000 * 60 * 15 webpackServer: serverConfig // handle => { indexRenderer} routerrouterrouterrouter
API
projectName
project name of webpack entries that you want to server side rendering
// webpack config
...
entry: {
index: ['../path to app client entry'],
dashboard: ['../path to dashboard project client entry']
},
...
const indexRenderer = new VueSSR({
projectName: 'index',
webpackServer: serverConfig
})
const dashRenderer = new VueSSR({
projectName: 'dashboard',
webpackServer: serverConfig
})
rendererOptions
rendererOptions is Vue server renderer options
directives
Allows you to provide server-side implementations for your custom directives:
const indexRenderer = new VueSSR('index', {
directives: {
example (vnode, directiveMeta) {
// transform vnode based on directive binding metadata
}
}
}, serverConfig)
cache
const indexRenderer = new VueSSR('index', {
cache: require('lru-cache')({
max: 1000,
maxAge: 1000 * 60 * 15
})
}, serverConfig)
webpackServer
for example webpack.server.js
const serverConfig = require('path to webpack.server.js')
const indexRenderer = new VueSSR({
projectName: 'index',
webpackServer: serverConfig
})
AppHtml
The default AppHtml is {{ APP }}
, rendering of the server side is replaced by AppHtml
{{ APP }}
...
You can also customize it
const indexRenderer = new VueSSR({ projectName: 'index', webpackServer: serverConfig, AppHtml: '<div id="app"></div>'})
contextHandler
const indexRenderer = new VueSSR({
contextHandler: function (req) {
return {
url: req.url,
ua: uaParser(req.headers['user-agent'])
}
}
})
defaultHeadData
const indexRenderer = defaultHeadData: baseTitle: 'VueSSR' baseKeywords: ',vue-ssr' baseDescription: 'Vue server-side rendering' title: '' description: '' keywords: ''
head meta(charset="utf-8") meta(name="renderer", content="webkit") title {{ _VueSSR_Title }} meta(name="viewport", content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no") meta(name="keywords", content="{{ _VueSSR_Keywords }}") meta(name="description", content="{{ _VueSSR_Description }}")
server-entry.js
export default context => {
router.push(context.url)
return Promise.all(router.getMatchedComponents().map(component => {
if (component.preFetch) {
return component.preFetch(store, router, context)
}
})).then(() => {
context.initialState = store.state
return app
})
}
simple component
{ contextheadData = title: 'this article's title description: 'about this article' keywords: 'Vue,vuejs,javascript' return Promise }
Example
License
MIT