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

来源:https://www.cnblogs.com/qqloving/archive/2023/11/14/17832471.html
-Advertisement-
Play Games

vue 最有代表性質的就是.VUE 的文件,每一個vue文件都是一個組件,那麼vue 組件的編譯過程是什麼樣的呢 Vue 單文件組件 (SFC)和指令 ast 語法樹 一個 Vue 單文件組件 (SFC),通常使用 *.vue 作為文件擴展名,它是一種使用了類似 HTML 語法的自定義文件格式,用於 ...


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

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

test
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 零基礎快速上手STM32開發(手把手保姆級教程) 1. 前言 作為一名嵌入式工程師,STM32 是必須要學習的一款單片機,同時這款單片機資料足夠多,而且比較簡單,非常適合初學者入門。 STM32 是一款由 STMicroelectronics 公司開發的 32 位微控制器,由於其強大的處理能力和廣泛 ...
  • 插入到集合中: 要將記錄(在MongoDB中稱為文檔)插入到集合中,使用insert_one()方法。insert_one()方法的第一個參數是一個包含文檔中每個欄位的名稱和值的字典。 import pymongo myclient = pymongo.MongoClient("mongodb:// ...
  • 事務的底層原理 在事務的實現機制上,MySQL 採用的是 WAL:Write-ahead logging,預寫式日誌,機制來實現的。 在使用 WAL 的系統中,所有的修改都先被寫入到日誌中,然後再被應用到系統中。通常包含 redo 和 undo 兩部分信息。 為什麼需要使用 WAL,然後包含 red ...
  • 項目應用中需要用mysql執行一下命令行.幾經搜索可以安裝lib_mysqludf_sys插件可以實現 本地window環境安裝(mysql8.0 , 64位 , 使用lib_mysqludf_sys.dll文件) -- 查看環境中插件目錄 show variables like '%plugin% ...
  • NineData DSQL 是針對多個同異構資料庫系統進行跨庫查詢的功能,當前支持對錶和視圖進行 SELECT 操作。您可以在一個查詢中訪問多個資料庫,獲取分散在各個資料庫中的有用信息,並且將這些信息聚合為一份查詢結果返回,輕鬆實現跨多個庫、多個數據源,乃至跨多個異構數據源的數據查詢。 ...
  • 火山引擎DataTester上線的「集成工作台」功能,能夠將DataTester的能力與企業自身的系統進行打通,減少系統之間的多次跳轉。幫助企業打造專屬AB平臺,滿足企業的個性化訴求,大幅降低企業服務的應用成本並提升用戶使用體驗。該功能可以通過完善的引導,進行一站式的定製、發佈、嵌出,幫助企業打造專... ...
  • 原文地址: Android app的暗黑模式適配實現 - Stars-One的雜貨小窩 很久之前放在草稿箱的一篇簡單筆記,是之前藍奏雲批量下載工具Android版本實現暗黑主題的適配記錄 本文所說的這裡的暗黑主題,應該只支持Android10系統,不過我手頭的Flyme系統(Android9)上測試 ...
  • 在日常的 JavaScript 編碼中,我們經常使用解構語法來提取對象中的屬性。假設我們有一個名為 fetchResult 的對象,代表從介面返回的數據,其中包含一個欄位名為 data。 const fetchResult = { data: null }; 在提取 data 欄位時,為了避免介面未 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...