vue3源碼學習api-vue-sfc文件編譯

vue 最有代表性質的就是.VUE 的文件,每一個vue文件都是一個組件,那麼vue 組件的編譯過程是什麼樣的呢

Vue 單文件組件 (SFC)和指令 ast 語法樹

一個 Vue 單文件組件 (SFC),通常使用 *.vue 作爲文件擴展名,它是一種使用了類似 HTML 語法的自定義文件格式,用於定義 Vue 組件。一個 Vue 單文件組件在語法上是兼容 HTML 的。

每一個 *.vue 文件都由三種頂層語言塊構成:<template><script><style>,以及一些其他的自定義塊:

<template>
  <div class="example">{{ msg }}</div>
</template>

<script>
export default {
  data() {
    return {
      msg: 'Hello world!'
    }
  }
}
</script>

<style>
.example {
  color: red;
}
</style>

<custom1>
  This could be e.g. documentation for the component.
</custom1>

關於sfc 這裏有非常詳細的介紹 https://github.com/vuejs/core/tree/main/packages/compiler-sfc

編譯解析和轉換工作流程

可以在流程圖中看到先對整個文件進行解析 識別出 出<template><script><style> 模塊 在各自解析

                                  +--------------------+
                                  |                    |
                                  |  script transform  |
                           +----->+                    |
                           |      +--------------------+
                           |
+--------------------+     |      +--------------------+
|                    |     |      |                    |
|  facade transform  +----------->+ template transform |
|                    |     |      |                    |
+--------------------+     |      +--------------------+
                           |
                           |      +--------------------+
                           +----->+                    |
                                  |  style transform   |
                                  |                    |
                                  +--------------------+

1.在facade轉換中,使用parse API將源解析爲描述符,並基於該描述符生成上述facade模塊代碼;

2.在腳本轉換中,使用“compileScript”處理腳本。這可以處理諸如“<script setup>”和CSS變量注入之類的功能。或者,這可以直接在facade模塊中完成(代碼內聯而不是導入),但需要將“導出默認值”重寫爲臨時變量(爲此提供了方便的“重寫默認值”API),因此可以將其他選項附加到導出的對象。

3.在模板轉換中,使用“compileTemplate”將原始模板編譯爲渲染函數代碼。

4.在樣式轉換中,使用“compileStyle”編譯原始CSS以處理“<style-scoped>”、“<style-module>”和CSS變量注入。

compile 和parse

在 packages/vue/src/index.ts 文件中可以看到
https://github.com/vuejs/core/blob/main/packages/vue/src/index.ts

import { compile, CompilerOptions, CompilerError } from '@vue/compiler-dom'

export { compileToFunction as compile }

vue 到處了一個 compile 方便對 <template> 中的內容進行編譯,返回一個渲染函數
到@vue/compiler-dom 中看看

import {
  baseCompile,
  baseParse,
  CompilerOptions,
  CodegenResult,
  ParserOptions,
  RootNode,
  noopDirectiveTransform,
  NodeTransform,
  DirectiveTransform
} from '@vue/compiler-core'
import { parserOptions } from './parserOptions'
import { transformStyle } from './transforms/transformStyle'
import { transformVHtml } from './transforms/vHtml'
import { transformVText } from './transforms/vText'
import { transformModel } from './transforms/vModel'
import { transformOn } from './transforms/vOn'
import { transformShow } from './transforms/vShow'
import { transformTransition } from './transforms/Transition'
import { stringifyStatic } from './transforms/stringifyStatic'
import { ignoreSideEffectTags } from './transforms/ignoreSideEffectTags'
import { extend } from '@vue/shared'

export { parserOptions }

export function compile(  template: string,
  options: CompilerOptions = {})={

}

export function parse(template: string, options: ParserOptions = {}): RootNode {
  return baseParse(template, extend({}, parserOptions, options))
}

export * from './runtimeHelpers'
export { transformStyle } from './transforms/transformStyle'
export { createDOMCompilerError, DOMErrorCodes } from './errors'
export * from '@vue/compiler-core'


我們可以看到很多有用的東西

  • 1 導出了parse,方法,用來對.vue 文件解析
  • 2 導出了compile 方法,用來對<template> 模板進行編譯,
  • 3 導入了很多常用的vue 指令,如果想要了解vue 指令是如何實現的就可以順着進去看看
import { transformVHtml } from './transforms/vHtml'
import { transformVText } from './transforms/vText'
import { transformModel } from './transforms/vModel'
import { transformOn } from './transforms/vOn'
import { transformShow } from './transforms/vShow'

可以簡單的寫一些代碼看看 在nodejs上執行一下 vue 也是支持服務器端渲染的

import { compile,} from 'vue'
import { parse } from '@vue/compiler-dom'
const vuefile="<template><h1>hello</h1></template><style></style><script></script> ";
const templateStr="<template><h1>hello</h1></template> ";
console.log(vuefile)
let RenderFunction = compile(vuefile)
console.log(RenderFunction)
const result = parse(vuefile)
console.log(result)

看看輸出

 node test.mjs
<template><h1>hello</h1></template><style></style><script></script> 
[Vue warn]: Template compilation error: Tags with side effect (<script> and <style>) are ignored in client component templates.
1  |  <template><h1>hello</h1></template><style></style><script></script> 
   |                                     ^^^^^^^^^^^^^^^
[Vue warn]: Template compilation error: Tags with side effect (<script> and <style>) are ignored in client component templates.
1  |  <template><h1>hello</h1></template><style></style><script></script> 
   |                                                    ^^^^^^^^^^^^^^^^^
[Function: render] { _rc: true }
{
  type: 0,
  children: [
    {
      type: 1,
      ns: 0,
      tag: 'template',
      tagType: 0,
      props: [],
      isSelfClosing: false,
      children: [Array],
      loc: [Object],
      codegenNode: undefined
    },
    {
      type: 1,
      ns: 0,
      tag: 'style',
      tagType: 0,
      props: [],
      isSelfClosing: false,
      children: [],
      loc: [Object],
      codegenNode: undefined
    },
    {
      type: 1,
      ns: 0,
      tag: 'script',
      tagType: 0,
      props: [],
      isSelfClosing: false,
      children: [],
      loc: [Object],
      codegenNode: undefined
    }
  ],
  helpers: Set(0) {},
  components: [],
  directives: [],
  hoists: [],
  imports: [],
  cached: 0,
  temps: 0,
  codegenNode: undefined,
  loc: {
    start: { column: 1, line: 1, offset: 0 },
    end: { column: 69, line: 1, offset: 68 },
    source: '<template><h1>hello</h1></template><style></style><script></script> '
  }
}
可以看到compile 返回了一個渲染用的函數
parse 對文件解析返回的數據結構裏面包含3個模塊

指令

所有的指令都在 transforms 這個文件夾下面
https://github.com/vuejs/core/tree/main/packages/compiler-dom/src/transforms

vue 模板中各種內置的指令都是在這裏引入的 看一下最簡單 vshow

import { DirectiveTransform } from '@vue/compiler-core'
import { createDOMCompilerError, DOMErrorCodes } from '../errors'
import { V_SHOW } from '../runtimeHelpers'

export const transformShow: DirectiveTransform = (dir, node, context) => {
  const { exp, loc } = dir
  if (!exp) {
    context.onError(
      createDOMCompilerError(DOMErrorCodes.X_V_SHOW_NO_EXPRESSION, loc)
    )
  }

  return {
    props: [],
    needRuntime: context.helper(V_SHOW)
  }
}

可以看到這裏不是對vshow的定義,因爲這個模塊是編譯
指令的定義定義在這個文件夾下
https://github.com/vuejs/core/tree/main/packages/runtime-dom/src/directives
這是vshow
https://github.com/vuejs/core/blob/main/packages/runtime-dom/src/directives/vShow.ts

import { ObjectDirective } from '@vue/runtime-core'

export const vShowOldKey = Symbol('_vod')

interface VShowElement extends HTMLElement {
  // _vod = vue original display
  [vShowOldKey]: string
}

export const vShow: ObjectDirective<VShowElement> = {
  beforeMount(el, { value }, { transition }) {
    el[vShowOldKey] = el.style.display === 'none' ? '' : el.style.display
    if (transition && value) {
      transition.beforeEnter(el)
    } else {
      setDisplay(el, value)
    }
  },
  mounted(el, { value }, { transition }) {
    if (transition && value) {
      transition.enter(el)
    }
  },
  updated(el, { value, oldValue }, { transition }) {
    if (!value === !oldValue) return
    if (transition) {
      if (value) {
        transition.beforeEnter(el)
        setDisplay(el, true)
        transition.enter(el)
      } else {
        transition.leave(el, () => {
          setDisplay(el, false)
        })
      }
    } else {
      setDisplay(el, value)
    }
  },
  beforeUnmount(el, { value }) {
    setDisplay(el, value)
  }
}

function setDisplay(el: VShowElement, value: unknown): void {
  el.style.display = value ? el[vShowOldKey] : 'none'
}

// SSR vnode transforms, only used when user includes client-oriented render
// function in SSR
export function initVShowForSSR() {
  vShow.getSSRProps = ({ value }) => {
    if (!value) {
      return { style: { display: 'none' } }
    }
  }
}

vshow 是指令中最賤的一個主要對 style.display 的修改
vshow 有關的定義主要表現在 beforeMount、mounted、updated、beforeUnMount 這四個生命週期中
而且充分考慮了動畫 和沒有動畫兩種情況

可視化的查看編譯轉換結果play 工具

https://play.vuejs.org/
源碼在這裏 運維官方的打開很慢
https://github.com/vuejs/repl#readme
可以查看對3個模塊編譯後的效果

新概念概念 打開新世界的大門

在baseCompile 方法中

const ast = isString(template) ? baseParse(template, options) : template

可以看到這個變量名 ast 那麼什麼事ast 呢

在計算機科學中,抽象語法樹(Abstract Syntax Tree,AST),或簡稱語法樹(Syntax tree),是源代碼語法結構的一種抽象表示。 它以樹狀的形式表現編程語言的語法結構,樹上的每個節點都表示源代碼中的一種結構。 之所以說語法是“抽象”的,是因爲這裏的語法並不會表示出真實語法中出現的每個細節。

這是一個可以查看一段js對應的語法樹的網站
https://astexplorer.net/
如果我們要解析一段內容,先獲取這段內容的語法樹,往往更容易解析

js 的語法樹工具
https://github.com/facebook/jscodeshift

通過語法樹工具根號查看一些結構 如果有需求也可以用在其他用途

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章