Skip to content

Commit

Permalink
use component name for SSR caching (also allow full externalization)
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Aug 11, 2016
1 parent 1cde06b commit 0e75fb9
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 44 deletions.
105 changes: 67 additions & 38 deletions packages/vue-server-renderer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@
This package offers Node.js server-side rendering for Vue 2.0.

- [Installation](#installation)
- [API](#api)
- [Renderer Options](#renderer-options)
- [Why Use `bundleRenderer`?](#why-use-bundlerenderer)
- [Creating the Server Bundle](#creating-the-server-bundle)
- [Component Caching](#component-caching)
- [Client Side Hydration](#client-side-hydration)

## Installation

``` bash
Expand Down Expand Up @@ -100,31 +108,6 @@ bundleRenderer
.pipe(writableStream)
```

## Creating the Server Bundle

The application bundle can be generated by any build tool, so you can easily use Webpack + `vue-loader` with the bundleRenderer. You do need to use a slightly different webpack config and entry point for your server-side bundle, but the difference is rather minimal:

1. add `target: 'node'`, and use `output: { libraryTarget: 'commonjs2' }` for your webpack config.

2. In your server-side entry point, export a function. The function will receive the render context object (passed to `bundleRenderer.renderToString` or `bundleRenderer.renderToStream`), and should return a Promise, which should eventually resolve to the app's root Vue instance:

``` js
// server-entry.js
import Vue from 'vue'
import App from './App.vue'

const app = new Vue(App)

// the default export should be a function
// which will receive the context of the render call
export default context => {
// data pre-fetching
return app.fetchServerData(context.url).then(() => {
return app
})
}
```

## Renderer Options

### directives
Expand All @@ -147,9 +130,7 @@ As an example, check out [`v-show`'s server-side implementation](https://github.

### cache

> Note: this option has changed and is different from versions <= 2.0.0-alpha.8.
Provide a cache implementation. The cache object must implement the following interface:
Provide a [component cache](#component-caching) implementation. The cache object must implement the following interface:

``` js
{
Expand Down Expand Up @@ -189,12 +170,63 @@ const renderer = createRenderer({
})
```

## Component-Level Caching
## Why Use `bundleRenderer`?

In a typical Node.js app, the server is a long-running process. If we directly require our application code, the instantiated modules will be shared across every request. This imposes some inconvenient restrictions to the application structure: we will have to avoid any use of global stateful singletons (e.g. the store), otherwise state mutations caused by one request will affect the result of the next.

Instead, it's more straightforward to run our app "fresh" for each request, so that we don't have to think about avoiding state contamination across requests. This is exactly what `bundleRenderer` helps us achieve.

## Creating the Server Bundle

The application bundle can be generated by any build tool, so you can easily use Webpack + `vue-loader` with the bundleRenderer. You do need to use a slightly different webpack config and entry point for your server-side bundle, but the difference is rather minimal:

1. add `target: 'node'`, and use `output: { libraryTarget: 'commonjs2' }` for your webpack config. Also, it's probably a good idea to [externalize your dependencies](#externals).

2. In your server-side entry point, export a function. The function will receive the render context object (passed to `bundleRenderer.renderToString` or `bundleRenderer.renderToStream`), and should return a Promise, which should eventually resolve to the app's root Vue instance:

``` js
// server-entry.js
import Vue from 'vue'
import App from './App.vue'

const app = new Vue(App)

// the default export should be a function
// which will receive the context of the render call
export default context => {
// data pre-fetching
return app.fetchServerData(context.url).then(() => {
return app
})
}
```

### Externals

When using the `bundleRenderer`, we will by default bundle every dependency of our app into the server bundle as well. This means on each request these depdencies will need to be parsed and evaluated again, which is unnecessary in most cases.

We can optimize this by externalizing dependencies from your bundle. During the render, any raw `require()` calls found in the bundle will return the actual Node module from your rendering process. With Webpack, we can simply list the modules we want to externalize using the [`externals` config option](https://webpack.github.io/docs/configuration.html#externals):

``` js
// webpack.config.js
module.exports = {
// this will externalize all modules listed under "dependencies"
// in your package.json
externals: Object.keys(require('./package.json').dependencies)
}
```

### Externals Caveats

Since externalized modules will be shared across every request, you need to make sure that the dependency is **idempotent**. That is, using it across different requests should always yield the same result - it cannot have global state that may be changed by your application. Interactions between externalized modules are fine (e.g. using a Vue plugin).

## Component Caching

You can easily cache components during SSR by implementing the `serverCacheKey` function:

``` js
export default {
name: 'item', // required
props: ['item'],
serverCacheKey: props => props.item.id,
render (h) {
Expand All @@ -203,10 +235,15 @@ export default {
}
```

The cache key is per-component, and it should contain sufficient information to represent the shape of the render result. The above is a good implementation because the render result is solely determined by `props.item.id`. However, if the render result also relies on another prop, then you need to modify your `getCacheKey` implementation to take that other prop into account.
Note that cachable component **must also define a unique "name" option**. This is necessary for Vue to determine the identity of the component when using the
bundle renderer.

With a unique name, the cache key is thus per-component: you don't need to worry about two components returning the same key. A cache key should contain sufficient information to represent the shape of the render result. The above is a good implementation if the render result is solely determined by `props.item.id`. However, if the item with the same id may change over time, or if render result also relies on another prop, then you need to modify your `getCacheKey` implementation to take those other variables into account.

Returning a constant will cause the component to always be cached, which is good for purely static components.

### When to use component caching

If the renderer hits a cache for a component during render, it will directly reuse the cached result for the entire sub tree. So **do not cache a component containing child components that rely on global state**.

In most cases, you shouldn't and don't need to cache single-instance components. The most common type of components that need caching are ones in big lists. Since these components are usually driven by objects in database collections, they can make use of a simple caching strategy: generate their cache keys using their unique id plus the last updated timestamp:
Expand All @@ -215,14 +252,6 @@ In most cases, you shouldn't and don't need to cache single-instance components.
serverCacheKey: props => props.item.id + '::' + props.item.last_updated
```

## Externals

By default, we will bundle every dependency of our app into the server bundle as well. V8 is very good at optimizing running the same code over and over again, so in most cases the cost of re-running it on every request is a worthwhile tradeoff in return for more freedom in application structure.

You can also further optimize the re-run cost by externalizing dependencies from your bundle. When running the bundle, any raw `require()` calls found in the bundle will return the actual module from your rendering process. With Webpack, you can simply list the modules you want to externalize using the `externals` config option. This avoids having to re-initialize the same module on each request and can also be beneficial for memory usage.

However, since the same module instance will be shared across every request, you need to make sure that the dependency is **idempotent**. That is, using it across different requests should always yield the same result - it cannot have global state that may be changed by your application. Because of this, you should avoid externalizing Vue itself and its plugins.

## Client Side Hydration

In server-rendered output, the root element will have the `server-rendered="true"` attribute. On the client, when you mount a Vue instance to an element with this attribute, it will attempt to "hydrate" the existing DOM instead of creating new DOM nodes.
Expand Down
24 changes: 20 additions & 4 deletions src/server/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ import { encodeHTML } from 'entities'
import { compileToFunctions } from 'web/compiler/index'
import { createComponentInstanceForVnode } from 'core/vdom/create-component'

let warned = Object.create(null)
const warnOnce = msg => {
if (!warned[msg]) {
warned[msg] = true
console.warn(`\n\u001b[31m${msg}\u001b[39m\n`)
}
}

const normalizeAsync = (cache, method) => {
const fn = cache[method]
if (!fn) {
Expand Down Expand Up @@ -61,8 +69,9 @@ export function createRenderFunction (
// check cache hit
const Ctor = node.componentOptions.Ctor
const getKey = Ctor.options.serverCacheKey
if (getKey && cache) {
const key = Ctor.cid + '::' + getKey(node.componentOptions.propsData)
const name = Ctor.options.name
if (getKey && cache && name) {
const key = name + '::' + getKey(node.componentOptions.propsData)
if (has) {
has(key, hit => {
if (hit) {
Expand All @@ -81,14 +90,20 @@ export function createRenderFunction (
})
}
} else {
if (getKey) {
console.error(
if (getKey && !cache) {
warnOnce(
`[vue-server-renderer] Component ${
Ctor.options.name || '(anonymous)'
} implemented serverCacheKey, ` +
'but no cache was provided to the renderer.'
)
}
if (getKey && !name) {
warnOnce(
`[vue-server-renderer] Components that implement "serverCacheKey" ` +
`must also define a unique "name" option.`
)
}
renderComponent(node, write, next, isRoot)
}
} else {
Expand Down Expand Up @@ -213,6 +228,7 @@ export function createRenderFunction (
write: (text: string, next: Function) => void,
done: Function
) {
warned = Object.create(null)
activeInstance = component
normalizeRender(component)
renderNode(component._render(), write, done, true)
Expand Down
1 change: 1 addition & 0 deletions test/ssr/fixtures/cache.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Vue from '../../../dist/vue.common.js'

const app = {
name: 'app',
props: ['id'],
serverCacheKey: props => props.id,
render (h) {
Expand Down
4 changes: 2 additions & 2 deletions test/ssr/ssr-bundle-render.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ describe('SSR: bundle renderer', () => {
}
createRenderer('cache.js', renderer => {
const expected = '<div server-rendered="true">&sol;test</div>'
const key = '1::1'
const key = 'app::1'
renderer.renderToString((err, res) => {
expect(err).toBeNull()
expect(res).toBe(expected)
Expand Down Expand Up @@ -143,7 +143,7 @@ describe('SSR: bundle renderer', () => {
}
createRenderer('cache.js', renderer => {
const expected = '<div server-rendered="true">&sol;test</div>'
const key = '1::1'
const key = 'app::1'
renderer.renderToString((err, res) => {
expect(err).toBeNull()
expect(res).toBe(expected)
Expand Down

0 comments on commit 0e75fb9

Please sign in to comment.