跳到主要内容

SSR 和 Tree-shaking 的优化

也是优化手段

SSR 优化

  • 静态节点直接输出,绕过了 vdom
  • 动态节点,还是需要动态渲染

还是看 https://vue-next-template-explorer.netlify.app/ 这个

<div>
<span>hello vue3</span>
<span>hello vue3</span>
<span>hello vue3</span>
<span>{{ mgs }}</span>
</div>

生成 AST 树

import { createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createElementBlock as _createElementBlock } from "vue"

export function render(_ctx, _cache, $props, $setup, $data, $options) {
return (_openBlock(), _createElementBlock("div", null, [
_createElementVNode("span", null, "hello vue3"),
_createElementVNode("span", null, "hello vue3"),
_createElementVNode("span", null, "hello vue3"),
_createElementVNode("span", null, _toDisplayString(_ctx.mgs), 1 /* TEXT */)
]))
}

// Check the console for the AST

然后在 Options 里勾选 SSR, AST 树变化

静态节点直接输出,绕过了 vdom

import { mergeProps as _mergeProps } from "vue"
import { ssrRenderAttrs as _ssrRenderAttrs, ssrInterpolate as _ssrInterpolate } from "vue/server-renderer"

export function ssrRender(_ctx, _push, _parent, _attrs, $props, $setup, $data, $options) {
const _cssVars = { style: { color: _ctx.color }}
_push(`<div${
_ssrRenderAttrs(_mergeProps(_attrs, _cssVars))
}><span>hello vue3</span><span>hello vue3</span><span>hello vue3</span><span>${
_ssrInterpolate(_ctx.mgs)
}</span></div>`)
}

// Check the console for the AST

Tree-shaking 的优化

  • 编译时,根据不同的情况,引入不同的 API

只用到 reactive,编译时只会引入 reactive

import {toRefs, reactive} from 'vue'

export default {
setup() {
// 对象实现响应式,使用 reactive
const state = reactive({
name: 'lzw.',
age: 20
})
return state
}
}