38-mini-vue 实现解析 element

实现解析 element

  1. 思路
  • 区别与解析插值语法,解析 element 需要不同类型和方法, 尖角号和第一个字符是字母
  • 将解析完成后的代码都删掉
  1. 测试代码
js 复制代码
describe("element",()=> {
  it("simple element div",()=>{
    const ast = baseParse("<div></div>")
    expect(ast.children[0]).toStrictEqual({
      type: NodeTypes.ELEMENT,
      tag: "div"
    })
  })
})
  1. 效果实现
js 复制代码
// compiler-core/src/parse.ts
function parseChildren(context) {
  const nodes: any[] = []
  let node:any
  const s = context.source
  if (s.startsWith('{{')) {
     node = parseInterpolation(context)
  } else if(s[0] === '<') { // ✅ 匹配出标签
    if(/[a-z]/i.test(context.source[1])){ // ✅
      console.log('解析到标签');
      node = parseElement(context) // 处理标签
    }
  }
  nodes.push(node)
  return nodes
}

function parseElement(context) { // ✅
  let element = parseTag(context, TagType.Start ) // ✅ 处理前标签
  parseTag(context, TagType.End) // ✅ 处理后标签
  return element
}
function parseTag(context, type: TagType) { // ✅
  // 1. 解析 tag
  const match:any = /^<\/?([a-z]*)/i.exec(context.source)
  const tag = match[1]

  // 2. 删除处理完成的代码
  advanceBy(context, match[0].length)
  advanceBy(context, 1)
  if(type === TagType.End) return
  return {
      type: NodeTypes.ELEMENT,
      tag
    }
}
相关推荐
We་ct2 小时前
LeetCode 3. 无重复字符的最长子串:滑动窗口最优解演进与解析
前端·算法·leetcode·typescript
奔跑的web.2 小时前
前端使用7种设计模式的核心原则
前端·javascript·设计模式·typescript·vue
蜕变菜鸟2 小时前
折叠页面 css
前端
菩提小狗2 小时前
小迪安全2022-2023|第35天:WEB攻防-通用漏洞&XSS跨站&反射&存储&DOM&盲打&劫持|web安全|渗透测试|
前端·安全·xss
子春一2 小时前
Flutter for OpenHarmony:构建一个专业级 Flutter 节拍器,深入解析定时器、状态同步与音乐节奏交互设计
javascript·flutter·交互
这个昵称也不能用吗?3 小时前
React 19 【use】hook使用简介
前端·react.js·前端框架
web小白成长日记3 小时前
修复 Storybook MDX 中 “does not provide an export named ‘ArgsTable‘” 的实战
前端
Aotman_3 小时前
Vue <template v-for> key should be placed on the <template> tag.
前端·javascript·vue.js
摘星编程3 小时前
在OpenHarmony上用React Native:自定义useTranslation翻译功能
javascript·react native·react.js