關於kaiteUI中通過json數據實現代碼渲染器
前言
上禮拜筆者分享了搭建UI框架的技術棧,其中一個較爲關鍵的技術——代碼渲染器,由於篇幅問題放到了今天這篇博客中給大家做一個詳細的分析解讀。
在這裏先分析一下上篇博客內容—— 基於vue3.0 + vite + TypeScript 實現一個UI框架 - kaiteUI,這篇主要是通過基於vue3.0 + vite + TypeScript
技術框架來實現一個UI框架,筆者自己搭建框架的初衷是運用並鞏固最近學習的vue3.0新特性。
技術棧
廢話不多說,先給大家分享一下實現代碼渲染器的關鍵技術棧。
VUE3.0
前端主流框架(react,vue,angular)之一,更適合開發靈活度高且複雜的應用vite
是一個由原生 ESM 驅動的 Web 開發構建工具compiler-core
核心作用是將字符串轉換成 抽象對象語法樹ASTjson
是一種輕量級的數據交換格式prismjs
一款輕量級、可擴展的語法高亮顯示工具
需求分析
在思考需求分析之前我們先來看看kaiteUI官網的效果演示:
由上面的圖我們可以分析出,kaiteUI官網主要又以下幾個部分組成:
- 屬性功能概述(title)
主要展示組件當前屬性的屬性關鍵字 - 組件展示部分(componentShow)
負責將指定屬性的組件展示,並且讓用戶能夠與其進行交互。 - 代碼展示模塊(demoCode)
對各個組件代碼示例進行展示,並給出使用示例源碼,主要方便使用者瞭解各個組件的使用方法。
技術實現
實現原理
筆者大致總結的流程如下圖所示:
關鍵技術
vue3.0中的自定義塊
這邊用到的關鍵技術是在vite官網看到的一個文檔,上面表示——Vite
支持Vue SFC中的自定義塊。只需要在配置文件中給vueCustomBlockTransforms
爲自定義塊添加一系列的轉換函數即可使用。
官方給的代碼示例爲:
// vite.config.js
export default {
vueCustomBlockTransforms: {
i18n: ({
code }) => {
// i18n用於國際化翻譯
// return transformed code
}
}
}
出於模塊化的思想,我們將每個組件增加一個自定義塊來存放屬性的描述內容,並利用vueCustomBlockTransforms
爲自定義塊添加一系列的轉換函數。
vue3.0中compiler-core
下面是我在一個博客上找到的圖,他對compiler-core
的工作流程概括的比較完整。compiler-core
負責「Vue3」中核心編譯相關的能力,這包括解析(parse)模板、轉化 AST 抽象語法樹(transform)、代碼生成(generate)等三個過程,它們之間的工作流如下圖所示:
而在kaiteUI這個項目中我們只用到了baseparse
這個功能函數,也就是將我們的組件模板渲染成了一個AST抽象樹。
然後筆者對AST樹數據結構進行分析,進入 compiler-core
目錄下,結構一目瞭然。這裏說下 _tests_ 目錄,是vue
的jest
測試用例。
閱讀源碼前先看看用例,對閱讀源碼有很大幫助哦。
如下,測試一個簡單的text,執行parse
方法之後,得到 ast,期望 ast 的第一個節點與定義的對象是一致的。
同理其他的模塊測試用例,在閱讀源碼前可以先瞄一眼,知道這個模塊如何使用,輸入輸出是啥。
當讀取到是純文本結點時得到的AST抽象樹的數據結構
test('simple text', () => {
const ast = parse('some text')
const text = ast.children[0] as TextNode
expect(text).toStrictEqual({
type: NodeTypes.TEXT,
content: 'some text',
isEmpty: false,
loc: {
start: {
offset: 0, line: 1, column: 1 },
end: {
offset: 9, line: 1, column: 10 },
source: 'some text'
}
})
})
當讀取到是HTML元素結點時得到的AST抽象樹的數據結構
test('simple div', () => {
const ast = baseParse('<div>hello</div>')
const element = ast.children[0] as ElementNode
expect(element).toStrictEqual({
type: NodeTypes.ELEMENT,
ns: Namespaces.HTML,
tag: 'div',
tagType: ElementTypes.ELEMENT,
codegenNode: undefined,
props: [],
isSelfClosing: false,
children: [
{
type: NodeTypes.TEXT,
content: 'hello',
loc: {
start: {
offset: 5, line: 1, column: 6 },
end: {
offset: 10, line: 1, column: 11 },
source: 'hello'
}
}
],
loc: {
start: {
offset: 0, line: 1, column: 1 },
end: {
offset: 16, line: 1, column: 17 },
source: '<div>hello</div>'
}
})
})
由此我們可以得出content
和loc.source
是我們想要的關鍵屬性,在源碼中筆者找到相關屬性存儲內容的區別,當讀取到文本結點時,會出現content
屬性,content
存放的是文本內容,而當讀取到HTML結點時loc.source
是包含html標籤的內容。
prismjs語法高亮
PrismJS
是一款輕量級、可擴展的語法高亮顯示工具,在支持現代 Web 標準基礎下增加了更多可選的風格插件。
PrismJS
支持自定義擴展代碼的語言、主題和插件選項,勾選自己常用的代碼語言和主題風格以及增強插件,將定製好的代碼文件 prism.css
和 prism.js
如下方式鏈接到頁面,再使用 <pre>
<code>
編輯方式編寫代碼文章即可展現漂亮的代碼高亮。
代碼實現
組件使用示例模塊
此處以Switch
組件爲例,其中爲自定義塊
<!-- 自定義塊 -->
<demo>
支持 disabled
</demo>
<template>
<Switch v-model:value="bool" disabled />
</template>
<script lang="ts">
//導入組件
import Switch from "../../../lib/Switch.vue";
//導入ref
import {
ref } from "vue";
export default {
components: {
Switch,
},
setup() {
//實現動態綁定
const bool = ref(false);
return {
bool,
};
},
};
</script>
Vue SFC中的自定義塊解析模塊
這裏還有一個插件——將md文件渲染成js文件到頁面中,此處不做詳細介紹,後面我會單獨拿一篇博客來講解其技術實現
// @ts-nocheck
import {
md } from "./plugins/md";
import fs from "fs";
import {
baseParse } from "@vue/compiler-core";
export default {
base: "./",
assetsDir: "assets",
//此處模塊功能——將md文件渲染到頁面中,將單獨介紹其技術實現
plugins: [md()],
//通過 vueCustomBlockTransforms 選項來指定自定義區塊的轉換規則
vueCustomBlockTransforms: {
demo: (options) => {
//將options解構賦值
const {
code, path } = options;
//異步讀取文件內容,並轉爲string類型
const file = fs.readFileSync(path).toString();
//將讀取到的文件中的自定義快渲染爲AST
const parsed = baseParse(file).children.find((n) => n.tag === "demo");
//讀取自定義模塊中的文本內容
const title = parsed.children[0].content;
//將讀取文件中的自定義塊切分,並轉爲字符串類型
const main = file.split(parsed.loc.source).join("").trim();
//以JSON數據類型返回
return `export default function (Component) {
Component.__sourceCode = ${
JSON.stringify(main)}
Component.__sourceCodeTitle = ${
JSON.stringify(title)}
}`.trim();
},
},
};
我們添加了一個 vueCustomBlockTransforms
對象, 該對象將鍵 demo
(我們的塊名)映射到返回虛擬 js 文件的函數中。
在 vueCustomBlockTransforms
中添加額外字段 __sourceCode
和__sourceCodeTitle
, 該字段映射到我們在任何自定義 <demo>
塊中聲明的代碼。
然後,我們在路由生成代碼<h2>{ { component.__sourceCodeTitle }}</h2>
中使用此代碼。
代碼渲染模塊
<template>
<div class="demo">
<!-- 渲染屬性文本內容 -->
<h2>{
{ component.__sourceCodeTitle }}</h2>
<!-- 功能展示 -->
<div class="demo-component">
<!-- vue3.0中綁定組件的指令 -->
<component :is="component" />
</div>
<div class="demo-actions">
<Button @click="toggleCode" v-if="codeVisible">隱藏代碼</Button>
<Button @click="toggleCode" v-else>查看代碼</Button>
</div>
<!-- 渲染代碼 -->
<div :class="'demo-code' + [codeVisible ? ' code-show ' : ' code-hidden ']">
<pre class="language-html" v-html="html" />
</div>
</div>
</template>
<script lang="ts">
import Button from "../lib/Button.vue";
import "prismjs";
import "prismjs/themes/prism.css";
import {
computed, ref } from "vue";
const Prism = (window as any).Prism;
export default {
components: {
Button,
},
props: {
component: Object,
},
setup(props) {
const html = computed(() => {
//代碼高亮
return Prism.highlight(
props.component.__sourceCode,
Prism.languages.html,
"html"
);
});
const toggleCode = () => (codeVisible.value = !codeVisible.value);
const codeVisible = ref(false);
return {
Prism,
html,
codeVisible,
toggleCode,
};
},
};
</script>
成果展示
kaite-ui官網頁面:kaite-ui官網頁面
github開源地址:github開源地址