国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

淺談vue中.vue文件解析流程

2019-11-19 13:58:04
字體:
供稿:網(wǎng)友

我們平時寫的 .vue 文件稱為 SFC(Single File Components),本文介紹將 SFC 解析為 descriptor 這一過程在 vue 中是如何執(zhí)行的。

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 兩個函數(shù),之后調(diào)用了 parseHTML 方法來對 .vue 文件內(nèi)容踐行編譯。

那么這個 parseHTML 方法是做啥的呢?

parseHTML 方法

該方法看名字就知道是一個 html-parser,可以簡單理解為,解析到每個起始標簽時,調(diào)用 option 中的 start;每個標簽結(jié)束時,調(diào)用 option 中的 end。

對應(yīng)到這里,就是分別調(diào)用 parseComponent 方法中定義的 start 和 end 函數(shù)。

在 parseComponent 中維護一個 depth 變量,在 start 中將 depth++ ,在 end 中 depth-- 。那么,每個 depth === 0 的標簽就是我們需要獲取的信息,包含 template、script、style 以及一些自定義標簽。

start

每當遇到一個起始標簽時,執(zhí)行 start 函數(shù)。

1、記錄下 currentBlock。

每個 currentBlock 包含以下內(nèi)容:

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

2、根據(jù) tag 名稱,將 currentBlock 對象在返回結(jié)果對象中。

返回結(jié)果對象定義為 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

每當遇到一個結(jié)束標簽時,執(zhí)行 end 函數(shù)。

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 對象即為我們需要的結(jié)果。

生成 .js ?

compiler.parseComponent(file, [options]) 得到的只是一個組件的 SFCDescriptor ,最終編譯成.js 文件是交給 vue-loader 等庫來做的。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 大埔区| 许昌县| 化隆| 徐水县| 含山县| 顺平县| 崇文区| 大邑县| 屏南县| 军事| 灵宝市| 囊谦县| 朔州市| 焦作市| 龙泉市| 兴安盟| 淳安县| 丰宁| 叙永县| 鹿泉市| 达孜县| 泰和县| 龙口市| 米林县| 九台市| 松潘县| 德安县| 兖州市| 临泽县| 贡嘎县| 定日县| 赤壁市| 资阳市| 海伦市| 房山区| 祁阳县| 甘洛县| 吴堡县| 黄龙县| 兰州市| 蓝田县|