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
通过语法树工具根号查看一些结构 如果有需求也可以用在其他用途
vue3源码学习api-vue-sfc文件编译的更多相关文章
- Vue源码学习1——Vue构造函数
Vue源码学习1--Vue构造函数 这是我第一次正式阅读大型框架源码,刚开始的时候完全不知道该如何入手.Vue源码clone下来之后这么多文件夹,Vue的这么多方法和概念都在哪,完全没有头绪.现在也只 ...
- Vue源码学习二 ———— Vue原型对象包装
Vue原型对象的包装 在Vue官网直接通过 script 标签导入的 Vue包是 umd模块的形式.在使用前都通过 new Vue({}).记录一下 Vue构造函数的包装. 在 src/core/in ...
- Vue源码学习三 ———— Vue构造函数包装
Vue源码学习二 是对Vue的原型对象的包装,最后从Vue的出生文件导出了 Vue这个构造函数 来到 src/core/index.js 代码是: import Vue from './instanc ...
- Vue2.x源码学习笔记-Vue构造函数
我们知道使用vue.js开发应用时,都是new Vue({}/*options*/) 那Vue构造函数上有哪些静态属性和方法呢?其原型上又有哪些方法呢? 一般我都会在浏览器中输入Vue来look se ...
- Vue源码学习一 ———— Vue项目目录
Vue 目录结构 可以在 github 上通过这款 Chrome 插件 octotree 查看Vue的文件目录.也可以克隆到本地.. Vue 是如何规划目录的 scripts ------------ ...
- Vue2.x源码学习笔记-Vue源码调试
如果我们不用单文件组件开发,一般直接<script src="dist/vue.js">引入开发版vue.js这种情况下debug也是很方便的,只不过vue.js文件代 ...
- vue 源码学习三 vue中如何生成虚拟DOM
vm._render 生成虚拟dom 我们知道在挂载过程中, $mount 会调用 vm._update和vm._render 方法,vm._updata是负责把VNode渲染成真正的DOM,vm._ ...
- Vue2.x源码学习笔记-Vue静态方法和静态属性整理
Vue静态方法和静态属性,其实直接在浏览器中可以查看到的,如下 圈起来的是其静态属性,但是有的属性对象中的属性的值又是函数.未圈起来的则是函数. 其实它来自如下各个目录下的js文件 // src/co ...
- Vue2.x源码学习笔记-Vue实例的属性和方法整理
还是先从浏览器直观的感受下实例属性和方法. 实例属性: 对应解释如下: vm._uid // 自增的id vm._isVue // 标示是vue对象,避免被observe vm._renderProx ...
- 【js】vue 2.5.1 源码学习 (十一) 模板编译compileToFunctions渲染函数
大体思路(九) 本节内容: 1. compileToFunctions定位 1. compileToFunctions定位 ==> createCompiler = createCompiler ...
随机推荐
- itest(爱测试) 4.5.1 发布,开源BUG 跟踪管理 & 敏捷测试管理软件
本次发布一共6个更新(其中一个4.5.0的重大BUG,不得不先发布4.5.1).4.5.0中增加ldap 登录支持时,引入一个BUG,新增的itest本地用户不能登录,除非重启. V4.5.1详情如 ...
- 🐞vue兄弟组件中方法互相调用
场景:父组件中同时引入两个子组件(A和B),此时B组件点击按钮需要调用A组件里面的方法 方案1:vue的事件总线 方案2:自定义事件($emit) 最终方案:方案2 父组件 具体操作 B组件上添加一个 ...
- Linu部署服务启停脚本
Linux项目部署启停 WEB应用(WAR包)部署 实际开发中,难免遇见新业务项目构建.项目重构(重新优化整个项目的架构,相当于重写),也可能是项目拆分多个模块,也可能部分拆分,但项目的模块化分离,就 ...
- SQL练习之打卡记录数据统计类问题
最近老婆的公司,关闭了OA系统中,各类打卡时间数据统计的功能,为了不麻烦老婆手算,就做了一个简单的打卡系统,方便自动统计老婆想要知道的各类数据. 做的过程中就遇到了几个还挺有意思的SQL,这里写成一篇 ...
- 简单实现Viper配置管理
本文由 ChatMoney团队出品 简介 前面实现的一个简易suno-api.是使用cookie来获取suno-token发起请求的.当时并没有通过配置的方式来获取cookie,而是直接在代码中写死了 ...
- DP Record
从 2024/5/4 往后开始记录捏. T1. 给你一棵树,定义一个集合的权值为 \(\dfrac{\sum_{x\in S}V_x}{\sum_{x\in S}C_x}\).若一个点 \(\in S ...
- HP惠普战66电源黄灯闪烁无法充电
HP惠普战66电源黄灯闪烁无法充电 TYPE-C PD 无法充电. 解决办法:关机状态下,拔除外部设备,长按电源键30秒以释放主板静电,再插电源线可以开机.
- C#.NET HTTPS 双向证书 请求被中止: 未能创建 SSL/TLS 安全通道。
请求被中止: 未能创建 SSL/TLS 安全通道. 用mmc 给私钥证书添加Everyone 的权限.
- 时间格式化转换及时间比较compareTo,Controller层接收参数格式化,从数据源头解决时间格式错误数据对接口的影响
时间格式化转换及时间比较compareTo,Controller层接收参数格式化,从数据源头解决时间格式错误数据对接口的影响 /** * 时间格式的转换:在具体报错的地方做转换,可能不能从根本上面解决 ...
- 实验一:Wireshark工具的使用
1.0 [实验目的] 了解Wireshark.TCP协议的概念,掌握Wireshark抓包工具的使用.FTP的搭建和登录,学会对Wireshark抓包结果的分析. 2.0[知识点] Wireshark ...