Skip to content

Commit

Permalink
docs for ssr
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Jun 28, 2016
1 parent dd1c936 commit 3c523f2
Show file tree
Hide file tree
Showing 3 changed files with 213 additions and 6 deletions.
209 changes: 207 additions & 2 deletions packages/vue-server-renderer/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,210 @@
# vue-server-renderer

> This package is auto-generated. For pull requests please see `src/entries/web-server-renderer.js`
> This package is auto-generated. For pull requests please see [src/entries/web-server-renderer.js](https://github.com/vuejs/vue/blob/next/src/entries/web-server-renderer.js).
Documentation coming soon.
This package offers Node.js server-side rendering for Vue 2.0.

## Installation

``` bash
npm install vue-server-renderer
```

``` js
const ssr = require('vue-server-renderer')
```

## API

### ssr.createRenderer([[rendererOptions](#renderer-options)])

Create a `renderer` instance.

``` js
const renderer = ssr.createRenderer()
```

---

### renderer.renderToString(vm, cb)

Render a Vue instance to string. The callback is a standard Node.js callback that receives the error as the first argument:

``` js
const Vue = require('vue')
const ssr = require('vue-server-renderer')

const renderer = ssr.createRenderer()
const vm = new Vue({
render (h) {
return h('div', 'hello')
}
})

renderer.renderToString(vm, (err, html) => {
console.log(html) // -> <div server-rendered="true">hello</div>
})
```

---

### renderer.renderToStream(vm)

Render a Vue instance in streaming mode. Returns a Node.js readable stream.

``` js
// example usage with express
app.get('/', (req, res) => {
const vm = new App({ url: req.url })
const stream = renderer.renderToStream(vm)

res.write(`<!DOCTYPE html><html><head><title>...</title></head><body>`)

stream.on('data', chunk => {
res.write(chunk)
})

stream.on('end', () => {
res.end('</body></html>')
})
})
```

---

### ssr.createBundleRenderer(code, [[rendererOptions](#renderer-options)])

Creates a `bundleRenderer` instance using pre-bundled application code (see [Creating the Server Bundle](#creating-the-server-bundle)). For each render call, the code will be re-run in a new context using Node.js' `vm` module. This ensures your application state is discrete between requests, and you don't need to worry about structuring your application in a limiting pattern just for the sake of SSR.

``` js
const bundleRenderer = ssr.createBundleRenderer(code)
```

---

### bundleRenderer.renderToString([context], cb)

Render the bundled app to a string. Same callback interface with `renderer.renderToString`. The optional context object will be passed to the bundle's exported function.

``` js
bundleRenderer.renderToString({ url: '/' }, (err, html) => {
// ...
})
```

---

### bundleRenderer.renderToStream([context])

Render the bundled app to a stream. Same stream interface with `renderer.renderToStream`. The optional context object will be passed to the bundle's exported function.

``` js
bundleRenderer
.renderToStream({ url: '/' })
.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

Allows you to provide server-side implementations for your custom directives:

``` js
const renderer = createRenderer({
directives: {
example (vnode, directiveMeta) {
// transform vnode based on directive binding metadata
}
}
})
```

As an example, check out [`v-show`'s server-side implementation](https://github.com/vuejs/vue/blob/next/src/platforms/web/server/directives/show.js).

---

### cache

Specify cache options. Passed directly to [lru-cache](https://github.com/isaacs/node-lru-cache). The default is `{ max: 5000 }`.

``` js
const renderer = createRenderer({
cache: {
max: 10000
}
})
```

## Component-Level Caching

You can easily cache components during SSR by implementing the `server.getCacheKey` function:

``` js
export default {
props: ['item'],
server: {
getCacheKey: props => props.item.id
},
render (h) {
return h('div', this.item.id)
}
}
```

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.

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

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:

``` js
server: {
getCacheKey: props => props.item.id + '::' + props.item.last_updated
}
```

## 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.

In development mode, Vue will assert the client-side generated virtual DOM tree matches the DOM structure rendered from the server. If there is a mismatch, it will bail hydration, discard existing DOM and render from scratch. **In production mode, this assertion is disabled for maximum performance.**

### Hydration Caveats

One thing to be aware of when using SSR + client hydration is some special HTML structures that may be altered by the browser. For example, when you write this in a Vue template:

``` html
<table>
<tr><td>hi</td></tr>
</table>
```

The browser will automatically inject `<tbody>` inside `<table>`, however, the virtual DOM generated by Vue does not contain `<tbody>`, so it will cause a mismatch. To ensure correct matching, make sure to write valid HTML in your templates.
8 changes: 5 additions & 3 deletions packages/vue-template-compiler/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ npm install vue-template-compiler
```

``` js
var compiler = require('vue-template-compiler')
const compiler = require('vue-template-compiler')
```

## API
Expand All @@ -30,7 +30,9 @@ Compiles a template string and returns compiled JavaScript code. The returned re

Note the returned function code uses `with` and thus cannot be used in strict mode code.

**Options**
#### Options

It's possible to hook into the compilation process to support custom template features. **However, beware that by injecting custom compile-time modules, your templates will not work with other build tools built on standard built-in modules, e.g `vue-laoder` and `vueify`.**

The optional `options` object can contain the following:

Expand Down Expand Up @@ -76,6 +78,6 @@ This is only useful at runtime with pre-configured builds, so it doesn't accept
Parse a SFC (single-file component, or `*.vue` file) into a [descriptor](https://github.com/vuejs/vue/blob/next/flow/compiler.js#L131). This is used in SFC build tools like `vue-loader` and `vueify`.
**Options**
#### Options
- `pad`: with `{ pad: true }`, the extracted content for each block will be padded with newlines to ensure that the line numbers align with the original file. This is useful when you are piping the extracted content into other pre-processors, as you will get correct line numbers if there are any syntax errors.
2 changes: 1 addition & 1 deletion src/entries/web-compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export { compileToFunctions } from 'web/compiler/index'

export function compile (
template: string,
options?: Object
options?: CompilerOptions
): CompiledResult {
options = options || {}
const errors = []
Expand Down

0 comments on commit 3c523f2

Please sign in to comment.