vue 파일의 TS 코드를 단계별로 분석해 보세요.

青灯夜游
풀어 주다: 2023-04-24 17:43:43
앞으로
1321명이 탐색했습니다.

우리는 vue 파일이 '템플릿', '스크립트', '스타일' 세 가지 유형의 코드로 구성되어 있다는 것을 알고 있습니다. <script lang="ts"></script> 태그의 ts 코드를 분석하려면 어떻게 해야 하나요? <script lang="ts"></script>标签内的ts代码,要怎么做呢?

vue 파일의 TS 코드를 단계별로 분석해 보세요.

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

以下测试代码为例:

<template>
  <div>
    {{ testRef }}
  </div>
</template>
<script setup>
import { ref } from &#39;vue&#39;
const testRef = ref(&#39;test&#39;)  
</script>
<style scoped>
.test-page {
  background-color: #fff;
}
</style>
로그인 후 복사

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

截屏2023-04-22 下午9.51.56.png

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

代码如下:

const vueCompiler = require(&#39;@vue/compiler-dom&#39;)

const analyseCode = `<template>
<div>
  {{ testRef }}
</div>
</template>
<script setup>
import { ref } from &#39;vue&#39;
const testRef = ref(&#39;test&#39;)  
</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 = &#39;&#39; 
  children.forEach(element => {
    if (element.tag == &#39;script&#39;) {
      tsCode = element.children[0].content;
    }
  })

  console.log(tsCode)
}

parseVue(analyseCode)
로그인 후 복사

运行结果:

截屏2023-04-22 下午10.30.33.png

2.第二步:通过typescript解析

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

以上面代码为例:

const vueCompiler = require(&#39;@vue/compiler-dom&#39;)
const tsCompiler = require(&#39;typescript&#39;) 

const analyseCode = `<template>
<div>
  {{ testRef }}
</div>
</template>
<script setup>
import { ref } from &#39;vue&#39;
const testRef = ref(&#39;test&#39;)  
</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 = &#39;&#39; 
  children.forEach(element => {
    if (element.tag == &#39;script&#39;) {
      tsCode = element.children[0].content;
    }
  })

  console.log(tsCode)

  // 将ts代码转化为AST
  // 第一个参数为命名,可以随意填,
  // 第二个参数是需要生成AST的源代码字符串
  // 第三个参数表示TS编译器版本
  // 第四个参数表示是否添加parent节点信息
  const ast = tsCompiler.createSourceFile(&#39;testCode&#39;, tsCode, tsCompiler.ScriptTarget.Latest, true)
  console.log(ast)
  return ast
}


parseVue(analyseCode)
로그인 후 복사

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

截屏2023-04-22 下午10.42.49.png

完整的AST explorer

截屏2023-04-22 下午11.00.05.png

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 语法等语句vue 파일의 TS 코드를 단계별로 분석해 보세요.

1단계: @를 전달합니다. vue/compiler-dom 컴파일러 이 파서는

를 구문 분석하는 데 사용됩니다.다음 테스트 코드는 예입니다.

rrreee위 코드를 AST Explorer, 파서 선택 @vue/compiler-dom [관련 권장 사항: vuejs 비디오 튜토리얼, 웹 프론트- 개발 종료]

🎜스크린샷 2023-04-22 9.51.56 pm 🎜🎜오른쪽에서 AST 구조를 찾을 수 있습니다. 코드는 템플릿, 스크립트, 스타일의 세 부분으로 구문 분석됩니다. AST를 통해 스크립트 태그에 있는 코드의 문자열 정보를 얻을 수 있습니다. 노드 속성(그림의 녹색 상자 부분) 🎜🎜코드는 다음과 같습니다: 🎜rrreee🎜실행 결과: 🎜🎜 스크린샷 2023- 04-22 PM 10.30.33.png🎜

2. 2단계: typescript

를 통해 구문 분석 🎜첫 번째 단계에서는 @vue/compiler-dom을 통해 vue 파일의 스크립트 태그에서 코드 문자열을 추출했습니다. 다음으로 추출된 코드 문자열을 typescript/ code>해당 AST를 처리하고 생성합니다. 🎜🎜위 코드를 예로 들어보세요: 🎜rrreee🎜실행 결과(그림이 완전하지 않음)🎜🎜<img src="https://img.php.cn/upload/article/000/000/024/560fbde805eda96e8b1052055f0b313b%20-2.png" alt="스크린샷 2023-04-22 PM 10.42.49.png" loading="lazy">🎜🎜완료<a href="https://www.php.cn/link/ef4c88811e3816f40407421553982e89" target="_blank" title="https://astexplorer.net/?spm=taofed.bloginfo.blog.3.3ba15ac8enL4hJ#/gist/dcd9b0bf2cfcfdda5e22762c98e8b845/336467e39a86f826257ff91e8f4646b005ce753c ref=" nof ollow no opener noreferrer>AST Explorer🎜🎜🎜 🎜<h2><strong>3. 3단계: 모든 수준에서 AST 노드 탐색 및 분석</strong></h2>🎜TypeScript의 CompilerAPI를 통해 AST 노드 탐색: <code>forEachChild🎜rrreee 🎜그런 다음 코드에 따라 공통 리터럴, 식별자, 표현식, 명령문, 모듈 구문, 클래스 구문 및 기타 명령문에 각각 해당 AST 노드 유형이 있으며 해당 분석이 수행될 수 있습니다(자세한 내용은 이 섹션의 지식에서 확인할 수 있습니다). 온라인으로 검색하고 시각화 도구 🎜 AST 탐색기 🎜 관찰과 결합) 🎜🎜 (학습 비디오 공유: 🎜vuejs 입문 튜토리얼🎜, 🎜기본 프로그래밍 비디오🎜)🎜

위 내용은 vue 파일의 TS 코드를 단계별로 분석해 보세요.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:juejin.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!