vite原理之解析.vue文件

简介: vite就是在本地启用了一个http服务器,然后将本地的文件通过浏览器的请求将本地的文件返回到浏览器;当然其中会有大量的解析,用于将文件内容解析为浏览器可以理解的内容

据说可以掌握的知识

  1. node express框架
  2. vue3
  3. ast树
  4. render函数
  5. 正则
  6. sfc
  7. esm模块

我的理解

按原文来讲,vite就是在本地启用了一个http服务器,然后将本地的文件通过浏览器的请求将本地的文件返回到浏览器;当然其中会有大量的解析,用于将文件内容解析为浏览器可以理解的内容

1. 依赖

"express": "^4.18.1", // 启动服务器
"vue": "^3.2.37" //处理和解析vue模板

2. 初始化文件,安装依赖

...略

3. 搭建服务器读取模板

3.1 启动文件server.js

const express = require("express")
var app = express()
const fs = require("fs")
const path = require("path")
const port = "3000"

app.get("/", (req, res, next)=>{
  //响应文本类型
  res.setHeader("content-type", "text/html")
  res.send(fs.readFileSync(path.resolve(__dirname, "./src/index.html")))
  res.end()
})

app.listen(port, ()=>{
  console.log(`the server is listen on ${port}`);
})

3.2 html模板文件src/index.html

<html>
<body>
  <div id="app">APP</div>
</body>

3.2 启动

node .server

3.3 效果

viteDemo-http预览.jpg

viteDemo-http预览.jpg

4. 读取vue文件

4.1 使用render函数读取

先使用vue的render函数来读取

  1. 新建 /src/index.js文件
import { createApp, h } from "vue";

createApp({
  render() {
    return h('div', {color: '#f00'}, "hello")
  }
})
.mount("#app")
  1. 修改server.js,以支持解析解析读取.js文件
const express = require("express")
var app = express()

const fs = require("fs")
const port = "3000"

app.get("/", (req, res, next)=>{
  res.setHeader("content-type", "text/html")
  res.send(fs.readFileSync("./src/index.html"))
  res.end()
})

app.get(/(.*)\.js$/, (req, res, next)=>{
  console.log(req.url, path.resolve(__dirname, "./src/"+ req.url));
  const p = fs.readFileSync(path.resolve(__dirname, "./src/"+ req.url), "utf-8");
  res.setHeader("content-type", "text/javascript")
  res.send(p)  
  res.end()
})
  1. 查看预览效果:

vite-vue-h函数预览,解析页面空白.png

vite-vue-h函数预览,解析页面空白.png

  1. 导致这个的原因是因为没法处理from 'vue',需要对/src/server.js进行一下改造:
app.get(/(.*)\.js$/, (req, res, next)=>{
  console.log(req.url, path.resolve(__dirname, "./src/"+ req.url));
  const p = fs.readFileSync(path.resolve(__dirname, "./src/"+ req.url), "utf-8");
  res.setHeader("content-type", "text/javascript")
-  res.send(p)  
+  res.send(reWritePath(p))
  res.end()
})

app.get(/^\/@module/, (req, res, next)=>{
  console.log(req.url, req.url.slice(9));
  # 将最终文件指向/node_modules/vue/package.json里的module配置
  const moduleFolder = path.resolve(__dirname, `./node_modules/${req.url.slice(9)}`)
  const modulePackageContent = require(moduleFolder+"/package.json").module
  const finalModulePath = path.join(moduleFolder, modulePackageContent)
  console.log("finalModulePath: ", finalModulePath);
  res.setHeader("content-type", "text/javascript")
  res.send(reWritePath(fs.readFileSync(finalModulePath, "utf-8")))
  res.end()
})

# 处理 import from "vue" 导出,将其转换成可识别路径
function reWritePath(content) {
  let reg = / from ['"](.*)['"]/g
  return content.replace(reg, (s1, s2)=>{
    console.log(s1, " ", s2);
    if(s2.startsWith(".") || s2.startsWith("./") || s2.startsWith("../")){
      return s1
    }else {
      return `from '/@module/${s2}'`
    }
  })
}
  1. 修改模板文件/src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app"></div>
  <script src="./index.js" type="module"></script>
</body>
</html>
  1. 预览效果

vite-vue-h函数预览.png
vite-vue-h函数预览.png

4.2 那么如何成功读取.vue文件,并将其渲染到浏览器页面呢?

这就需要用到改造/src/index文件

1. 新建/src/app.vue文件

<template>
  {{title}}
</template>
<script>
import {ref} from "vue"
export default {
  setup() {
    const title = ref("hello")
    return {
      title
    }
  }
}
</script>

<style>
*{
  color:#f00;
}
</style>

2. 修改/src/index.js文件

import { createApp} from "vue";
import app from "./app.vue"

createApp(app)
.mount("#app")

3. 预览报错

vite-vue-文件不识别.png

vite-vue-文件不识别.png

4. 这个错误是不识别vue后缀的请求导致的

4.1 解决方法就是添加处理以vue为后缀的请求

  1. 修改/server.js
app.get(/(.*)\.vue$/, (req, res, next)=>{
  // exclude request with ? which is template or style requestion
  const questUrl = req.url
  console.log("vue: ", req.url, path.resolve(__dirname, `./src/${questUrl}`));
  const content = fs.readFileSync(path.resolve(__dirname, `./src/${questUrl}`), 'utf-8')
  const contentAST = compilerSFC.parse(reWritePath(content))
  console.log("ast: ", contentAST);
  console.log("query: ", req.query);
})

此时,会返回一串ast树代码,然后query是个空对象
vite-vue-astTree.png

vite-vue-astTree.png

  1. 继续修改/server.js
app.get(/(.*)\.vue$/, (req, res, next)=>{
  // exclude request with ? which is template or style requestion
  const questUrl = req.url
  console.log("vue: ", req.url, path.resolve(__dirname, `./src/${questUrl}`));
  const content = fs.readFileSync(path.resolve(__dirname, `./src/${questUrl}`), 'utf-8')
  const contentAST = compilerSFC.parse(reWritePath(content))
  console.log("ast: ", contentAST);
  console.log("query: ", req.query);
  const scriptContent = contentAST.descriptor.script.content
  const script = scriptContent.replace("export default", "const _script = ")
  res.setHeader("content-type", "text/javascript")
  res.send(`
    ${reWritePath(script)}
    import {render as _render} from '${req.url}?type=template';
    import '${req.url}?type=style'
    _script.render = _render
    export default _script
  `)
  res.end()
})

通过compilerSFC插件,将.vue文件解析为ast树;从中的script字段的content获取到js内容;并且再次请求app.vue?type=template(请求模板内容)和app.vue?type=style(请求样式);将export default替换为const _script,并导出

  1. 预览效果:

vite-vue-v文件请求.png

vite-vue-v文件请求.png

  1. 请求返回内容

vite-vue-vue后缀请求返回内容.png

vite-vue-vue后缀请求返回内容.png

4.2 处理app.vue?type=templateapp.vue?type=style请求,继续修改/src/server文件

app.get(/(.*)\.vue$/, (req, res, next)=>{
  // exclude request with ? which is template or style requestion
  const questUrl = req.url.split('?')[0]
  console.log("vue: ", req.url, path.resolve(__dirname, `./src/${questUrl}`));
  const content = fs.readFileSync(path.resolve(__dirname, `./src/${questUrl}`), 'utf-8')
  const contentAST = compilerSFC.parse(reWritePath(content))
  console.log("ast: ", contentAST);
  console.log("query: ", req.query);
  // deal with sfc when req.query.type is empty
  if(!req.query.type) {
    const scriptContent = contentAST.descriptor.script.content
    const script = scriptContent.replace("export default", "const _script = ")
    res.setHeader("content-type", "text/javascript")
    res.send(`
      ${reWritePath(script)}
      import {render as _render} from '${req.url}?type=template';
      import '${req.url}?type=style'
      _script.render = _render
      export default _script
    `)
    res.end()
  }else if(req.query.type === 'template') {
    const templateContent = contentAST.descriptor.template.content;
    console.log("compiler: ", compilerDOM.compile(templateContent, {mode: "module"}));
    const renderContent = compilerDOM.compile(templateContent, {mode: "module"}).code
    console.log("code: ", renderContent);
    res.setHeader("content-type", "text/javascript")
    res.send(reWritePath(renderContent));
    res.end()
  }else if(req.query.type === 'style') {
    console.log(contentAST.descriptor.styles[0].content);
    const styleContent = contentAST.descriptor.styles[0].content.replace(/\s/g, "")
    res.setHeader("content-type", "text/javascript")
    res.send(`
      const style = document.createElement('style');
      style.innerHTML = '${styleContent}'
      document.head.appendChild(style)
    `);
    res.end()
  }
})

预览效果:
vite-vue-预览效果之没有process参数.png

vite-vue-预览效果之没有process参数.png

4.3. 修改/src/index.js,处理process参数

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app"></div>
  <script src="./index.js" type="module"></script>
+  <script>
+    window.process = {
+      env: {
+        NODE_ENV: "development"
+      }
+    }
+  </script>
</body>
</html>

预览效果:
添加process参数后的预览效果.png

添加process参数后的预览效果.png


5. 至此,vite解析.vue的原理基本脉络就清楚了

vite-vue-目录结构.png

vite-vue-目录结构.png

  1. package.json
{
  "name": "demo-viteCore",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1",
    "vue": "^3.2.37"
  }
}
  1. /src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app"></div>
  <script src="./index.js" type="module"></script>
  <script>
    window.process = {
      env: {
        NODE_ENV: "development"
      }
    }
  </script>
</body>
</html>
  1. /src/app.vue
<template>
  {{title}}
</template>
<script>
import {ref} from "vue"
export default {
  setup() {
    const title = ref("hello")
    return {
      title
    }
  }
}
</script>

<style>
*{
  color:#f00;
}
</style>
  1. /src/index.js
import { createApp} from "vue";
import app from "./app.vue"
createApp(app)
.mount("#app")
  1. /server.js
const express = require("express")
var app = express()

const compilerSFC = require("@vue/compiler-sfc")
const compilerDOM = require("@vue/compiler-dom")

const path = require("path")
const fs = require("fs")
const port = "3000"

app.get("/", (req, res, next)=>{
  res.setHeader("content-type", "text/html")
  res.send(fs.readFileSync("./src/index.html"))
  res.end()
})

app.get(/(.*)\.js$/, (req, res, next)=>{
  console.log(req.url, path.resolve(__dirname, "./src/"+ req.url));
  const p = fs.readFileSync(path.resolve(__dirname, "./src/"+ req.url), "utf-8");
  res.setHeader("content-type", "text/javascript")
  res.send(reWritePath(p))
  res.end()
})

app.get(/(.*)\.vue$/, (req, res, next)=>{
  // exclude request with ? which is template or style requestion
  const questUrl = req.url.split('?')[0]
  console.log("vue: ", req.url, path.resolve(__dirname, `./src/${questUrl}`));
  const content = fs.readFileSync(path.resolve(__dirname, `./src/${questUrl}`), 'utf-8')
  const contentAST = compilerSFC.parse(reWritePath(content))
  console.log("ast: ", contentAST);
  console.log("query: ", req.query);
  // deal with sfc when req.query.type is empty
  if(!req.query.type) {
    const scriptContent = contentAST.descriptor.script.content
    const script = scriptContent.replace("export default", "const _script = ")
    res.setHeader("content-type", "text/javascript")
    res.send(`
      ${reWritePath(script)}
      import {render as _render} from '${req.url}?type=template';
      import '${req.url}?type=style'
      _script.render = _render
      export default _script
    `)
    res.end()
  }else if(req.query.type === 'template') {
    const templateContent = contentAST.descriptor.template.content;
    console.log("compiler: ", compilerDOM.compile(templateContent, {mode: "module"}));
    const renderContent = compilerDOM.compile(templateContent, {mode: "module"}).code
    console.log("code: ", renderContent);
    res.setHeader("content-type", "text/javascript")
    res.send(reWritePath(renderContent));
    res.end()
  }else if(req.query.type === 'style') {
    console.log(contentAST.descriptor.styles[0].content);
    const styleContent = contentAST.descriptor.styles[0].content.replace(/\s/g, "")
    res.setHeader("content-type", "text/javascript")
    res.send(`
      const style = document.createElement('style');
      style.innerHTML = '${styleContent}'
      document.head.appendChild(style)
    `);
    res.end()
  }
})

app.get(/^\/@module/, (req, res, next)=>{
  console.log(req.url, req.url.slice(9));
  const moduleFolder = path.resolve(__dirname, `./node_modules/${req.url.slice(9)}`)
  const modulePackageContent = require(moduleFolder+"/package.json").module
  const finalModulePath = path.join(moduleFolder, modulePackageContent)
  console.log("finalModulePath: ", finalModulePath);
  res.setHeader("content-type", "text/javascript")
  res.send(reWritePath(fs.readFileSync(finalModulePath, "utf-8")))
  res.end()
})

function reWritePath(content) {
  let reg = / from ['"](.*)['"]/g
  return content.replace(reg, (s1, s2)=>{
    console.log(s1, " ", s2);
    if(s2.startsWith(".") || s2.startsWith("./") || s2.startsWith("../")){
      return s1
    }else {
      return `from '/@module/${s2}'`
    }
  })
}


app.listen(port, ()=>{
  console.log(`the server is listen on ${port}`);
})
相关文章
|
3月前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
349 2
|
2月前
|
缓存 JavaScript
vue中的keep-alive问题(2)
vue中的keep-alive问题(2)
320 137
|
6月前
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
830 0
|
6月前
|
JavaScript UED
用组件懒加载优化Vue应用性能
用组件懒加载优化Vue应用性能
|
5月前
|
人工智能 JSON JavaScript
VTJ.PRO 首发 MasterGo 设计智能识别引擎,秒级生成 Vue 代码
VTJ.PRO发布「AI MasterGo设计稿识别引擎」,成为全球首个支持解析MasterGo原生JSON文件并自动生成Vue组件的AI工具。通过双引擎架构,实现设计到代码全流程自动化,效率提升300%,助力企业降本增效,引领“设计即生产”新时代。
469 1
|
5月前
|
JavaScript 安全
在 Vue 中,如何在回调函数中正确使用 this?
在 Vue 中,如何在回调函数中正确使用 this?
295 0
|
6月前
|
JavaScript 前端开发 开发者
Vue 自定义进度条组件封装及使用方法详解
这是一篇关于自定义进度条组件的使用指南和开发文档。文章详细介绍了如何在Vue项目中引入、注册并使用该组件,包括基础与高级示例。组件支持分段配置(如颜色、文本)、动画效果及超出进度提示等功能。同时提供了完整的代码实现,支持全局注册,并提出了优化建议,如主题支持、响应式设计等,帮助开发者更灵活地集成和定制进度条组件。资源链接已提供,适合前端开发者参考学习。
500 17
|
6月前
|
JavaScript 前端开发 UED
Vue 表情包输入组件实现代码及详细开发流程解析
这是一篇关于 Vue 表情包输入组件的使用方法与封装指南的文章。通过安装依赖、全局注册和局部使用,可以快速集成表情包功能到 Vue 项目中。文章还详细介绍了组件的封装实现、高级配置(如自定义表情列表、主题定制、动画效果和懒加载)以及完整集成示例。开发者可根据需求扩展功能,例如 GIF 搜索或自定义表情上传,提升用户体验。资源链接提供进一步学习材料。
308 1
|
9月前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
921 29
|
9月前
|
前端开发 数据安全/隐私保护 CDN
二次元聚合短视频解析去水印系统源码
二次元聚合短视频解析去水印系统源码
392 4

推荐镜像

更多
  • DNS