一步步带你分析vue文件中的ts代码

广告:宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取~~~

一步步带你分析vue文件中的ts代码

我们知道vue文件是由'template'、'script'、'style'三种类型代码组合成的。如果要分析<script lang="ts"></script>标签内的ts代码,要怎么做呢?

1.第一步: 通过@vue/compiler-dom 编译器 这个parser来解析

以下测试代码为例:

<template>  <div>    {{ testRef }}  </div></template><script setup>import { ref } from 'vue'const testRef = ref('test')  </script><style scoped>.test-page {  background-color: #fff;}</style>
登录后复制

把上面的代码放到 AST explorer,parser 选择 @vue/compiler-dom 【相关推荐:vuejs视频教程、web前端开发】

可以发现,右侧的AST结构:代码被解析成 template、script和style这三部分,我们通过AST节点属性就可以获取到script标签内代码的字符串信息(图中的绿色框部分)。

代码如下:

const vueCompiler = require('@vue/compiler-dom')const analyseCode = `<template><div>  {{ testRef }}</div></template><script setup>import { ref } from 'vue'const testRef = ref('test')  </script><style scoped>.test-page {background-color: #fff;}</style>`const parseVue = (vueCode) => {  // 解析vue代码  const result = vueCompiler.parse(vueCode)  const children = result.children  // 获取script片段  let tsCode = ''   children.forEach(element => {    if (element.tag == 'script') {      tsCode = element.children[0].content;    }  })  console.log(tsCode)}parseVue(analyseCode)
登录后复制

运行结果:

2.第二步:通过typescript解析

在第一步中,我们通过@vue/compiler-dom提取出了 vue 文件 script标签内的代码字符串;接下来,把提取出的代码字符串交给 typescript处理,生成对应的 AST。

以上面代码为例:

const vueCompiler = require('@vue/compiler-dom')const tsCompiler = require('typescript') const analyseCode = `<template><div>  {{ testRef }}</div></template><script setup>import { ref } from 'vue'const testRef = ref('test')  </script><style scoped>.test-page {background-color: #fff;}</style>`const parseVue = (vueCode) => {  // 解析vue代码  const result = vueCompiler.parse(vueCode)  const children = result.children  // 获取script片段  let tsCode = ''   children.forEach(element => {    if (element.tag == 'script') {      tsCode = element.children[0].content;    }  })  console.log(tsCode)  // 将ts代码转化为AST  // 第一个参数为命名,可以随意填,  // 第二个参数是需要生成AST的源代码字符串  // 第三个参数表示TS编译器版本  // 第四个参数表示是否添加parent节点信息  const ast = tsCompiler.createSourceFile('testCode', tsCode, tsCompiler.ScriptTarget.Latest, true)  console.log(ast)  return ast}parseVue(analyseCode)
登录后复制

运行结果(图片不是完整的)

完整的AST explorer

3.第三步:遍历分析 AST 各级节点

通过TypeScript 的 CompilerAPI : forEachChild遍历AST节点

const ast = parseVue(analyseCode) // 上面示例的函数const walk  = (node) => {                        // AST遍历函数  tsCompiler.forEachChild(node, walk);          // 遍历AST节点  console.log(node);                            // 输出节点信息}walk(ast)
登录后复制

然后根据代码中常见的字面量、标识符、表达式、语句、模块语法、class 语法等语句各自都有对应的 AST 节点类型,就可以去做相应的分析了(这一块的详细知识可以网上搜下,可以结合可视化工具 AST explorer 观察)

(学习视频分享:vuejs入门教程、编程基础视频)

以上就是一步步带你分析vue文件中的ts代码的详细内容,更多请关注9543建站博客其它相关文章!

9543建站博客
一个专注于网站开发、微信开发的技术类纯净博客。
作者头像
admin创始人

肥猫,知名SEO博客站长,14年SEO经验。

上一篇:如何解决uniapp定位不准确问题
下一篇:vue项目前后端分离用cdn还是npm

发表评论

关闭广告
关闭广告