vue-server-renderer

此程序包是自动生成的. 有关拉取请求,请参阅 src/entries/web-server-renderer.js.

此软件包提供Vue 2.0的Node.js服务器端呈现。

(id:installation)
<a name="installation" />
<span id="installation">跳转到这里</span>
<a name="installation">安装</a>

安装

npm install vue-server-renderer

API

createRenderer([rendererOptions])

创建一个 renderer 实例.

const renderer = require('vue-server-renderer').createRenderer()

renderer.renderToString(vm, cb)

将Vue实例呈现为字符串。 回调是一个标准的Node.js回调,它接收错误作为第一个参数:

const Vue = require('vue')

const renderer = require('vue-server-renderer').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)

以流模式呈现Vue实例。 返回一个Node.js可读流。

// 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>')
  })
})

createBundleRenderer(bundle, [rendererOptions])

使用预编译的应用程序包创建 bundleRenderer . bundle 参数可以是以下之一:

  • 生成的bundle文件( .js.json )的绝对路径。 文件路径必须以/开头

  • vue-ssr-webpack-plugin生成的bundle对象.

  • 一个JavaScript代码字符串.

有关详细信息,请参阅 创建服务器包

对于每个render调用,代码将使用Node.js的 vm模块在一个新的上下文中重新运行。 这确保您的应用程序状态在请求之间是离散的,并且您不需要担心为了SSR而以限制模式构造应用程序。

const createBundleRenderer = require('vue-server-renderer').createBundleRenderer

// 绝对文件路径
let renderer = createBundleRenderer('/path/to/bundle.json')

// bundle对象
let renderer = createBundleRenderer({ ... })

// 代码(不推荐缺少源映射支持)
let renderer = createBundleRenderer(bundledCode)

bundleRenderer.renderToString([context], cb)

将捆绑的应用程序复制到字符串。 与renderer.renderToString相同的回调。 可选的上下文对象将被传递到bundle的导出函数。

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

bundleRenderer.renderToStream([context])

将捆绑的应用程序呈现到流。 与renderer.renderToStream相同的流。 可选的上下文对象将被传递到bundle的导出函数。

bundleRenderer
  .renderToStream({ url: '/' })
  .pipe(writableStream)

渲染器选项

缓存

提供组件缓存实现。 缓存对象必须实现以下接口(使用流标记):

type RenderCache = {
  get: (key: string, cb?: Function) => string | void;
  set: (key: string, val: string) => void;
  has?: (key: string, cb?: Function) => boolean | void;
};

一个典型的用法是传递一个 lru-cache:

const LRU = require('lru-cache')

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

注意,缓存对象应该至少实现getset 。 此外, gethas接受第二个参数作为回调,可以选择异步。 这允许缓存使用异步API,例如redis客户端:

const renderer = createRenderer({
  cache: {
    get: (key, cb) => {
      redisClient.get(key, (err, res) => {
        // handle error if any
        cb(res)
      })
    },
    set: (key, val) => {
      redisClient.set(key, val)
    }
  }
})

模版

New in 2.2.0

Provide a template for the entire page's HTML. The template should contain a comment `` which serves as the placeholder for rendered app content.
为整个网页的HTML提供模板。 模板应包含注释 ,作为呈现的应用内容的占位符。

In addition, when both a template and a render context is provided (e.g. when using the bundleRenderer), the renderer will also automatically inject the following properties found on the render context:
此外,当提供模板和渲染上下文时(例如,当使用bundleRenderer ),渲染器也将自动注入渲染上下文中找到的以下属性:

  • context.head: (string) any head markup that should be injected into the head of the page. 应该注入页面头部的任何头标记

  • context.styles: (string) any inline CSS that should be injected into the head of the page. Note that vue-loader 10.2.0+ (which uses vue-style-loader 2.0) will automatically populate this property with styles used in rendered components.应该注入页面头部的任何内联CSS。 请注意, vue-loader 10.2.0+(使用vue-style-loader 2.0)将使用渲染组件中使用的样式自动填充此属性

  • context.state: (Object) initial Vuex store state that should be inlined in the page as window.__INITIAL_STATE__. The inlined JSON is automatically sanitized with serialize-javascript.初始Vuex存储状态,应在页面中内联为window.INITIAL_STATE, 内联JSON将使用serialize-javascript自动进行清理

Example:

const renderer = createRenderer({
  template:
    '<!DOCTYPE html>' +
    '<html lang="en">' +
      '<head>' +
        '<meta charset="utf-8">' +
        // context.head will be injected here
        // context.styles will be injected here
      '</head>' +
      '<body>' +
        '<!--vue-ssr-outlet-->' + // <- app content rendered here
        // context.state will be injected here
      '</body>' +
    '</html>'
})

basedir

New in 2.2.0

Explicitly declare the base directory for the server bundle to resolve node_modules from. This is only needed if your generated bundle file is placed in a different location from where the externalized NPM dependencies are installed.

Note that the basedir is automatically inferred if you use vue-ssr-webpack-plugin or provide an absolute path to createBundleRenderer as the first argument, so in most cases you don't need to provide this option. However, this option does allow you to explicitly overwrite the inferred value.


directives

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

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.

Why Use bundleRenderer?

When we bundle our front-end code with a module bundler such as webpack, it can introduce some complexity when we want to reuse the same code on the server. For example, if we use vue-loader, TypeScript or JSX, the code cannot run natively in Node. Our code may also rely on some webpack-specific features such as file handling with file-loader or style injection with style-loader, both of which can be problematic when running inside a native Node module environment.

The most straightforward solution to this is to leverage webpack's target: 'node' feature and simply use webpack to bundle our code on both the client AND the server.

Having a compiled server bundle also provides another advantage in terms of code organization. In a typical Node.js app, the server is a long-running process. If we run our application modules directly, 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", in a sandboxed context for each request, so that we don't have to think about avoiding state contamination across requests.

Creating the Server Bundle

screen shot 2016-08-11 at 6 06 57 pm
screen shot 2016-08-11 at 6 06 57 pm

The application bundle can be either a string of bundled code (not recommended due to lack of source map support), or a special object of the following type:

type RenderBundle = {
  entry: string; // name of the entry file
  files: { [filename: string]: string; }; // all files in the bundle
  maps: { [filename: string]: string; }; // source maps
}

Although theoretically you can use any build tool to generate the bundle, it is recommended to use webpack + vue-loader + vue-ssr-webpack-plugin for this purpose. The plugin will automatically turn the build output into a single JSON file that you can then pass to createBundleRenderer. This setup works seamlessly even if you use webpack's on-demand code splitting features such as dynamic import().

The typical workflow is setting up a base webpack configuration file for the client-side, then modify it to generate the server-side bundle with the following changes:

  1. Set target: 'node' and output: { libraryTarget: 'commonjs2' } in your webpack config.

  2. Add vue-ssr-webpack-plugin to your webpack plugins. This plugin automatically generates the bundle as a single JSON file which contains all the files and source maps of the entire bundle. This is particularly important if you use Webpack's code-splitting features that result in a multi-file bundle.

  3. 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:

// 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
  })
}
  1. It's also a good idea to externalize your dependencies (see below).

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:

// 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:

export default {
  name: 'item', // required
  props: ['item'],
  serverCacheKey: props => props.item.id,
  render (h) {
    return h('div', this.item.id)
  }
}

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:

serverCacheKey: 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:

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容