欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈vue中.vue文件解析流程

程序员文章站 2022-06-24 22:05:27
我们平时写的 .vue 文件称为 sfc(single file components),本文介绍将 sfc 解析为 descriptor 这一过程在 vue 中是如何执行...

我们平时写的 .vue 文件称为 sfc(single file components),本文介绍将 sfc 解析为 descriptor 这一过程在 vue 中是如何执行的。

vue 提供了一个 compiler.parsecomponent(file, [options]) 方法,来将 .vue 文件解析成一个 descriptor:

// an object format describing a single-file component.
declare type sfcdescriptor = {
  template: ?sfcblock;
  script: ?sfcblock;
  styles: array<sfcblock>;
  customblocks: array<sfcblock>;
};

文件入口

解析 sfc 文件的入口在 src/sfc/parser.js 中,该文件 export 了 parsecomponent 方法, parsecomponent 方法用来对单文件组件进行编译。

接下来我们看看 parsecomponent 方法都做了哪些事情。

parsecomponent 方法

function start(tag, attrs, unary, start, end,){
}

function end(tag, start, end){
}

parsehtml(content, {
  start,
  end
})

parsecomponent 方法中定义了 start``end 两个函数,之后调用了 parsehtml 方法来对 .vue 文件内容践行编译。

那么这个 parsehtml 方法是做啥的呢?

parsehtml 方法

该方法看名字就知道是一个 html-parser,可以简单理解为,解析到每个起始标签时,调用 option 中的 start;每个标签结束时,调用 option 中的 end。

对应到这里,就是分别调用 parsecomponent 方法中定义的 start 和 end 函数。

在 parsecomponent 中维护一个 depth 变量,在 start 中将 depth++ ,在 end 中 depth-- 。那么,每个 depth === 0 的标签就是我们需要获取的信息,包含 template、script、style 以及一些自定义标签。

start

每当遇到一个起始标签时,执行 start 函数。

1、记录下 currentblock。

每个 currentblock 包含以下内容:

declare type sfcblock = {
  type: string;
  content: string;
  start?: number;
  end?: number;
  lang?: string;
  src?: string;
  scoped?: boolean;
  module?: string | boolean;
};

2、根据 tag 名称,将 currentblock 对象在返回结果对象中。

返回结果对象定义为 sfc,如果tag不是 script,style,template 中的任一个,就放在 sfc.customblocks 中。如果是style,就放在 sfc.styles 中。script 和 template 则直接放在 sfc 下。

if (isspecialtag(tag)) {
  checkattrs(currentblock, attrs)
  if (tag === 'style') {
    sfc.styles.push(currentblock)
  } else {
    sfc[tag] = currentblock
  }
} else { // custom blocks
  sfc.customblocks.push(currentblock)
}

end

每当遇到一个结束标签时,执行 end 函数。

1、如果当前是第一层标签(depth === 1),并且 currentblock 变量存在,那么取出这部分text,放在 currentblock.content 中。

if (depth === 1 && currentblock) {
 currentblock.end = start
 let text = deindent(content.slice(currentblock.start, currentblock.end))
 // pad content so that linters and pre-processors can output correct
 // line numbers in errors and warnings
 if (currentblock.type !== 'template' && options.pad) {
  text = padcontent(currentblock, options.pad) + text
 }
 currentblock.content = text
 currentblock = null
}

2、depth-- 。

得到 descriptor

在将 .vue 整个遍历一遍后,得到的 sfc 对象即为我们需要的结果。

生成 .js ?

compiler.parsecomponent(file, [options]) 得到的只是一个组件的 sfcdescriptor ,最终编译成.js 文件是交给 vue-loader 等库来做的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。