经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
学习Vite的原理
来源:jb51  时间:2022/2/14 13:36:03  对本文有异议

1. 概述

Vite是一个更轻、更快的web应用开发工具,面向现代浏览器。底层基于ECMAScript标准原生模块系统ES Module实现。他的出现是为了解决webpack冷启动时间过长以及Webpack HMR热更新反应速度慢等问题。

默认情况下Vite创建的项目是一个普通的Vue3应用,相比基于Vue-cli创建的应用少了很多配置文件和依赖。

Vite创建的项目所需要的开发依赖非常少,只有Vite@vue/compiler-sfc。这里面Vite是一个运行工具,compiler-sfc则是为了编译.vue结尾的单文件组件。在创建项目的时候通过指定不同的模板也可以支持使用其他框架例如React。项目创建完成之后可以通过两个命令启动和打包。

  1. # 开启服务器
  2. vite serve
  3. # 打包
  4. vite build

正是因为Vite启动的web服务不需要编译打包,所以启动的速度特别快,调试阶段大部分运行的代码都是你在编辑器中书写的代码,这相比于webpack的编译后再呈现确实要快很多。当然生产环境还是需要打包的,毕竟很多时候我们使用的最新ES规范在浏览器中还没有被支持,Vite的打包过程和webpack类似会将所有文件进行编译打包到一起。对于代码切割的需求Vite采用的是原生的动态导入来实现的,所以打包结果只能支持现代浏览器,如果需要兼容老版本浏览器可以引入Polyfill

使用Webpack打包除了因为浏览器环境并不支持模块化和新语法外,还有就是模块文件会产生大量的http请求。如果你使用模块化的方式开发,一个页面就会有十几甚至几十个模块,而且很多时候会出现几kb的文件,打开一个页面要加载几十个js资源这显然是不合理的。

  • Vite创建的项目几乎不需要额外的配置默认已经支持TS、Less, Sass,Stylus,postcss了,但是需要单独安装对应的编译器,同时默认还支持jsx和Web Assembly。
  • Vite带来的好处是提升开发者在开发过程中的体验,web开发服务器不需要等待即可立即启动,模块热更新几乎是实时的,所需的文件会按需编译,避免编译用不到的文件。并且开箱即用避免loader及plugins的配置。
  • Vite的核心功能包括开启一个静态的web服务器,能够编译单文件组件并且提供HMR功能。当启动vite的时候首先会将当前项目目录作为静态服务器的根目录,静态服务器会拦截部分请求,当请求单文件的时候会实时编译,以及处理其他浏览器不能识别的模块,通过websocket实现hmr。

2. 实现静态测试服务器

首先实现一个能够开启静态web服务器的命令行工具。vite1.x内部使用的是Koa来实现静态服务器。(ps:node命令行工具可以查看我之前的文章,这里就不介绍了,直接贴代码)。

  1. npm init
  2. npm install koa koa-send -D

工具bin的入口文件设置为本地的index.js

  1. #!/usr/bin/env node
  2.  
  3. const Koa = require('koa')
  4. const send = require('koa-send')
  5.  
  6. const app = new Koa()
  7.  
  8. // 开启静态文件服务器
  9. app.use(async (ctx, next) => {
  10. ? ? // 加载静态文件
  11. ? ? await send(ctx, ctx.path, { root: process.cwd(), index: 'index.html'})
  12. ? ? await next()
  13. })
  14.  
  15. app.listen(5000)
  16.  
  17. console.log('服务器已经启动 http://localhost:5000')

这样就编写好了一个node静态服务器的工具。

3. 处理第三方模块

我们的做法是当代码中使用了第三方模块(node_modules中的文件),可以通过修改第三方模块的路径给他一个标识,然后在服务器中拿到这个标识来处理这个模块。

首先需要修改第三方模块的路径,这里需要一个新的中间件来实现。判断一下当前返回给浏览器的文件是否是javascript,只需要看响应头中的content-type。如果是javascript需要找到这个文件中引入的模块路径。ctx.body就是返回给浏览器的内容文件。这里的数据是一个stream,需要转换成字符串来处理。

  1. const stream2string = (stream) => {
  2. ? ? return new Promise((resolve, reject) => {
  3. ? ? ? ? const chunks = [];
  4. ? ? ? ? stream.on('data', chunk => {chunks.push(chunk)})
  5. ? ? ? ? stream.on('end', () => { resolve(Buffer.concat(chunks).toString('utf-8'))})
  6. ? ? ? ? stream.on('error', reject)
  7. ? ? })
  8. }
  9.  
  10. // 修改第三方模块路径
  11. app.use(async (ctx, next) => {
  12. ? ? if (ctx.type === 'application/javascript') {
  13. ? ? ? ? const contents = await stream2string(ctx.body);
  14. ? ? ? ? // 将body中导入的路径修改一下,重新赋值给body返回给浏览器
  15. ? ? ? ? // import vue from 'vue', 匹配到from '修改为from '@modules/
  16. ? ? ? ? ctx.body = contents.replace(/(from\s+['"])(?![\.\/])/g, '$1/@modules/');
  17. ? ? }
  18. })

接着开始加载第三方模块, 这里同样需要一个中间件,判断请求路径是否是修改过的@module开头,如果是的话就去node_modules里面加载对应的模块返回给浏览器。这个中间件要放在静态服务器之前。

  1. // 加载第三方模块
  2. app.use(async (ctx, next) => {
  3. ? ? if (ctx.path.startsWith('/@modules/')) {
  4. ? ? ? ? // 截取模块名称
  5. ? ? ? ? const moduleName = ctx.path.substr(10);
  6. ? ? }
  7. })

拿到模块名称之后需要获取模块的入口文件,这里要获取的是ES Module模块的入口文件,需要先找到这个模块的package.json然后再获取这个package.json中的module字段的值也就是入口文件。

  1. // 找到模块路径
  2. const pkgPath = path.join(process.pwd(), 'node_modules', moduleName, 'package.json');
  3. const pkg = require(pkgPath);
  4. // 重新给ctx.path赋值,需要重新设置一个存在的路径,因为之前的路径是不存在的
  5. ctx.path = path.join('/node_modules', moduleName, pkg.module);
  6. // 执行下一个中间件
  7. awiat next();

这样浏览器请求进来的时候虽然是@modules路径,但是在加载之前将path路径修改为了node_modules中的路径,这样在加载的时候就会去node_modules中获取文件,将加载的内容响应给浏览器。

加载第三方模块:

  1. app.use(async (ctx, next) => {
  2. ? ? if (ctx.path.startsWith('/@modules/')) {
  3. ? ? ? ? // 截取模块名称
  4. ? ? ? ? const moduleName = ctx.path.substr(10);
  5. ? ? ? ? // 找到模块路径
  6. ? ? ? ? const pkgPath = path.join(process.pwd(), 'node_modules', moduleName, 'package.json');
  7. ? ? ? ? const pkg = require(pkgPath);
  8. ? ? ? ? // 重新给ctx.path赋值,需要重新设置一个存在的路径,因为之前的路径是不存在的
  9. ? ? ? ? ctx.path = path.join('/node_modules', moduleName, pkg.module);
  10. ? ? ? ? // 执行下一个中间件
  11. ? ? ? ? awiat next();
  12. ? ? }
  13. })

4. 单文件组件处理

之前说过浏览器是没办法处理.vue资源的, 浏览器只能识别js、css等常用资源,所以其他类型的资源都需要在服务端处理。当请求单文件组件的时候需要在服务器将单文件组件编译成js模块返回给浏览器。

所以这里当浏览器第一次请求App.vue的时候,服务器会把单文件组件编译成一个对象,先加载这个组件,然后再创建一个对象。

  1. import Hello from './src/components/Hello.vue'
  2. const __script = {
  3. ? ? name: "App",
  4. ? ? components: {
  5. ? ? ? ? Hello
  6. ? ? }
  7. }

接着再去加载入口文件,这次会告诉服务器编译一下这个单文件组件的模板,返回一个render函数。然后将render函数挂载到刚创建的组件选项对象上,最后导出选项对象。

  1. import { render as __render } from '/src/App.vue?type=template'
  2. __script.render = __render
  3. __script.__hmrId = '/src/App.vue'
  4. export default __script

也就是说vite会发送两次请求,第一次请求会编译单文件文件,第二次请求是编译单文件模板返回一个render函数。

编译单文件选项:

首先来实现一下第一次请求单文件的情况。需要把单文件组件编译成一个选项,这里同样用一个中间件来实现。这个功能要在处理静态服务器之后,处理第三方模块路径之前。

首先需要对单文件组件进行编译需要借助compiler-sfc

  1. // 处理单文件组件
  2. app.use(async (ctx, next) => {
  3. ? ? if (ctx.path.endsWith('.vue')) {
  4. ? ? ? ? // 获取响应文件内容,转换成字符串
  5. ? ? ? ? const contents = await streamToString(ctx.body);
  6. ? ? ? ? // 编译文件内容
  7. ? ? ? ? const { descriptor } = compilerSFC.parse(contents);
  8. ? ? ? ? // 定义状态码
  9. ? ? ? ? let code;
  10. ? ? ? ? // 不存在type就是第一次请求
  11. ? ? ? ? if (!ctx.query.type) {
  12. ? ? ? ? ? ? code = descriptor.script.content;
  13. ? ? ? ? ? ? // 这里的code格式是, 需要改造成我们前面贴出来的vite中的样子
  14. ? ? ? ? ? ? // import Hello from './components/Hello.vue'
  15. ? ? ? ? ? ? // export default {
  16. ? ? ? ? ? ? // ? ? ?name: 'App',
  17. ? ? ? ? ? ? // ? ? ?components: {
  18. ? ? ? ? ? ? // ? ? ? ? ?Hello
  19. ? ? ? ? ? ? // ? ? ?}
  20. ? ? ? ? ? ? // ?}
  21. ? ? ? ? ? ? // 改造code的格式,将export default 替换为const __script =
  22. ? ? ? ? ? ? code = code.relace(/export\s+default\s+/g, 'const __script = ')
  23. ? ? ? ? ? ? code += `
  24. ? ? ? ? ? ? ? ? import { render as __render } from '${ctx.path}?type=template'
  25. ? ? ? ? ? ? ? ? __script.rener = __render
  26. ? ? ? ? ? ? ? ? export default __script
  27. ? ? ? ? ? ? `
  28. ? ? ? ? }
  29. ? ? ? ? // 设置浏览器响应头为js
  30. ? ? ? ? ctx.type = 'application/javascript'
  31. ? ? ? ? // 将字符串转换成数据流传给下一个中间件。
  32. ? ? ? ? ctx.body = stringToStream(code);
  33. ? ? }
  34. ? ? await next()
  35. })
  36.  
  37. const stringToStream = text => {
  38. ? ? const stream = new Readable();
  39. ? ? stream.push(text);
  40. ? ? stream.push(null);
  41. ? ? return stream;
  42. }
  1. npm install @vue/compiler-sfc -D
  2.  

接着我们再来处理单文件组件的第二次请求,第二次请求url会带上type=template参数,需要将单文件组件模板编译成render函数。

首先需要判断当前请求中有没有type=template

  1. if (!ctx.query.type) {
  2. ? ? ...
  3. } else if (ctx.query.type === 'template') {
  4. ? ? // 获取编译后的对象 code就是render函数
  5. ? ? const templateRender = compilerSFC.compileTemplate({ source: descriptor.template.content })
  6. ? ? // 将render函数赋值给code返回给浏览器
  7. ? ? code = templateRender.code
  8. }

这里还要处理一下工具中的process.env,因为这些代码会返回到浏览器中运行,如果不处理会默认为node导致运行失败。可以在修改第三方模块路径的中间件中修改,修改完路径之后再添加一条修改process.env。

  1. // 修改第三方模块路径
  2. app.use(async (ctx, next) => {
  3. ? ? if (ctx.type === 'application/javascript') {
  4. ? ? ? ? const contents = await stream2string(ctx.body);
  5. ? ? ? ? // 将body中导入的路径修改一下,重新赋值给body返回给浏览器
  6. ? ? ? ? // import vue from 'vue', 匹配到from '修改为from '@modules/
  7. ? ? ? ? ctx.body = contents.replace(/(from\s+['"])(?![\.\/])/g, '$1/@modules/').replace(/process\.env\.NODE_ENV/g, '"development"');
  8. ? ? }
  9. })

至此就实现了一个简版的vite,当然这里我们只演示了.vue文件,对于css,less等其他资源都没有处理,不过方法都是类似的,感兴趣的同学可以自行实现。

  1. #!/usr/bin/env node
  2.  
  3. const path = require('path')
  4. const { Readable } = require('stream)
  5. const Koa = require('koa')
  6. const send = require('koa-send')
  7. const compilerSFC = require('@vue/compiler-sfc')
  8.  
  9. const app = new Koa()
  10.  
  11. const stream2string = (stream) => {
  12. ? ? return new Promise((resolve, reject) => {
  13. ? ? ? ? const chunks = [];
  14. ? ? ? ? stream.on('data', chunk => {chunks.push(chunk)})
  15. ? ? ? ? stream.on('end', () => { resolve(Buffer.concat(chunks).toString('utf-8'))})
  16. ? ? ? ? stream.on('error', reject)
  17. ? ? })
  18. }
  19.  
  20. const stringToStream = text => {
  21. ? ? const stream = new Readable();
  22. ? ? stream.push(text);
  23. ? ? stream.push(null);
  24. ? ? return stream;
  25. }
  26.  
  27. // 加载第三方模块
  28. app.use(async (ctx, next) => {
  29. ? ? if (ctx.path.startsWith('/@modules/')) {
  30. ? ? ? ? // 截取模块名称
  31. ? ? ? ? const moduleName = ctx.path.substr(10);
  32. ? ? ? ? // 找到模块路径
  33. ? ? ? ? const pkgPath = path.join(process.pwd(), 'node_modules', moduleName, 'package.json');
  34. ? ? ? ? const pkg = require(pkgPath);
  35. ? ? ? ? // 重新给ctx.path赋值,需要重新设置一个存在的路径,因为之前的路径是不存在的
  36. ? ? ? ? ctx.path = path.join('/node_modules', moduleName, pkg.module);
  37. ? ? ? ? // 执行下一个中间件
  38. ? ? ? ? awiat next();
  39. ? ? }
  40. })
  41.  
  42. // 开启静态文件服务器
  43. app.use(async (ctx, next) => {
  44. ? ? // 加载静态文件
  45. ? ? await send(ctx, ctx.path, { root: process.cwd(), index: 'index.html'})
  46. ? ? await next()
  47. })
  48.  
  49. // 处理单文件组件
  50. app.use(async (ctx, next) => {
  51. ? ? if (ctx.path.endsWith('.vue')) {
  52. ? ? ? ? // 获取响应文件内容,转换成字符串
  53. ? ? ? ? const contents = await streamToString(ctx.body);
  54. ? ? ? ? // 编译文件内容
  55. ? ? ? ? const { descriptor } = compilerSFC.parse(contents);
  56. ? ? ? ? // 定义状态码
  57. ? ? ? ? let code;
  58. ? ? ? ? // 不存在type就是第一次请求
  59. ? ? ? ? if (!ctx.query.type) {
  60. ? ? ? ? ? ? code = descriptor.script.content;
  61. ? ? ? ? ? ? // 这里的code格式是, 需要改造成我们前面贴出来的vite中的样子
  62. ? ? ? ? ? ? // import Hello from './components/Hello.vue'
  63. ? ? ? ? ? ? // export default {
  64. ? ? ? ? ? ? // ? ? ?name: 'App',
  65. ? ? ? ? ? ? // ? ? ?components: {
  66. ? ? ? ? ? ? // ? ? ? ? ?Hello
  67. ? ? ? ? ? ? // ? ? ?}
  68. ? ? ? ? ? ? // ?}
  69. ? ? ? ? ? ? // 改造code的格式,将export default 替换为const __script =
  70. ? ? ? ? ? ? code = code.relace(/export\s+default\s+/g, 'const __script = ')
  71. ? ? ? ? ? ? code += `
  72. ? ? ? ? ? ? ? ? import { render as __render } from '${ctx.path}?type=template'
  73. ? ? ? ? ? ? ? ? __script.rener = __render
  74. ? ? ? ? ? ? ? ? export default __script
  75. ? ? ? ? ? ? `
  76. ? ? ? ? } else if (ctx.query.type === 'template') {
  77. ? ? ? ? ? ? // 获取编译后的对象 code就是render函数
  78. ? ? ? ? ? ? const templateRender = compilerSFC.compileTemplate({ source: descriptor.template.content })
  79. ? ? ? ? ? ? // 将render函数赋值给code返回给浏览器
  80. ? ? ? ? ? ? code = templateRender.code
  81. ? ? ? ? }
  82. ? ? ? ? // 设置浏览器响应头为js
  83. ? ? ? ? ctx.type = 'application/javascript'
  84. ? ? ? ? // 将字符串转换成数据流传给下一个中间件。
  85. ? ? ? ? ctx.body = stringToStream(code);
  86. ? ? }
  87. ? ? await next()
  88. })
  89.  
  90. // 修改第三方模块路径
  91. app.use(async (ctx, next) => {
  92. ? ? if (ctx.type === 'application/javascript') {
  93. ? ? ? ? const contents = await stream2string(ctx.body);
  94. ? ? ? ? // 将body中导入的路径修改一下,重新赋值给body返回给浏览器
  95. ? ? ? ? // import vue from 'vue', 匹配到from '修改为from '@modules/
  96. ? ? ? ? ctx.body = contents.replace(/(from\s+['"])(?![\.\/])/g, '$1/@modules/').replace(/process\.env\.NODE_ENV/g, '"development"');
  97. ? ? }
  98. })
  99.  
  100. app.listen(5000)
  101.  
  102. console.log('服务器已经启动 http://localhost:5000')

到此这篇关于学习Vite的原理的文章就介绍到这了,更多相关Vite原理内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号