Home > headlines > body text

Understand Vue3+Vite3 source code in seconds, as long as you know these 20 libraries!

青灯夜游
Release: 2022-08-15 20:18:40
forward
4410 people have browsed it

As the saying goes: If a worker wants to do his job well, he must first sharpen his tools! Writing an open source project is no exception. Take the vue3 framework and vite tool which are very popular in China. The implementation and architectural design are both complex and complex. It is a huge project , and what supports the smooth operation of these projects is nothing but wheels after another. I happened to be reading the source code of vue3 and vite3 recently and found some more practical wheels. I will share them here. for everyone.

If you want to get involved in

front-end engineering, I believe there is always one of the tools below that you want!

1. picocolors

picocolors is a npm package that can modify the output character style in the terminal, to put it bluntly The point is to add color to the characters;

Understand Vue3+Vite3 source code in seconds, as long as you know these 20 libraries!

Some students may have thought, isn’t this the same as

chalk?

Yes, their functions are actually the same!

Why choose picocolors:

    No dependency package;
  • 14 times smaller than chalk and 2 times faster;
  • Support CJS and ESM projects;
So everyone knows what to choose!

Of course, because the

picocolors package is relatively small, the functional boundaries are not as comprehensive as chalk, but it can fully meet most needs such as some self-research. of.

Note:

  • Due to historical and other reasons

    vue3 is still using chalk;

  • vite has been fully replaced with

    picocolors as terminal style output;

  • However,

    chalk has been recently updated for optimization Dependent packages have been removed from the latest version v5;

2. prompts vs enquirer vs inquirer

At first glance, some students may be a little confused. In fact, one sentence explains: In fact, the three of them are used to

implement the command line interactive interface Tools;

are put together because the interactive tools used by

vue3 and vite are different;

Understand Vue3+Vite3 source code in seconds, as long as you know these 20 libraries!

Tool nameWhere to useSizeWeekly download volumegithub addresspromptsvite187 kB18,185,030##enquirerenquirerinquirerinquirer

npm download popularity trend in the past two years:

Understand Vue3+Vite3 source code in seconds, as long as you know these 20 libraries!

Simple summary:

  • Actually vite was originally used enquirer, but was replaced with prompts later in order to meet the bugs that occurred when users used it across platforms. Of course, It’s not that enquirer is not good, it’s just that the scenarios are different, so the choice will be different;

  • In fact, if you want to use in your own project As an interactive interface tool, I still recommend inquirer. After all, the popularity and functions of the community fully meet your needs.

3. cac

cac is a JavaScript library for building CLI applications;

In layman's terms, it means to add some customized commands to your cli tool, such as vite create, and the following create commands are added through cac;

Because this library is more suitable for some customized tool libraries, it is only used in vite. vue3 does not need this tool;

Why not use commander or yargs?

Mainly because vite’s tools are designed for some custom commands and other scenarios that are not particularly complex;

Let’s take a look at cac’s advantages:

  • Super lightweight: no dependencies, the size is several times smaller than commander and yargs;
  • Easy to learn: Only need to learn 4 APIs cli.option, cli.version, cli.help cli.parse It can handle most of the needs;
  • Powerful function: Enable the default command, you can use it as conveniently as using the git command, and there is verification of parameters and options, and automatic generation of help Waiting for the functions to be improved;

Of course, if you want to write a cli tool with more functions, you can also choose commander and yargs;

However, I still recommend cac for some small and medium-sized cli tools;

4. npm-run-all

npm-run-all is a cli tool that can execute multiple npm scripts in parallel or sequentially; npm-run-all in vite It is used in the tool source code;

In layman’s terms, it is to solve the problem that the official npm run command cannot run multiple scripts at the same time. It can put things like# The long list of commands ##npm run clean && npm run build:css && npm run build:js && npm run build:html is simplified to npm-run-all clean build:*# through glob syntax. ## One line command.

Provides three commands:

    npm-run-all
  • : can bring
      - The abbreviations of s
    • and -p parameters correspond to serial and parallel respectively;
      # 依次执行这三个任务命令
      npm-run-all clean lint build
      
      # 同时执行这两个任务命令
      npm-run-all --parallel lint build
      
      # 先串行执行 a 和 b, 再并行执行 c 和 d
      npm-run-all -s a b -p c d
      Copy after login
  • run-s
  • : is npm-run-all --serial abbreviation;
  • run-p
  • : is the abbreviation of npm-run-all --parallel;
The above is just a brief introduction. If you want to know more practical functions, you can go to the
official website

;Finally:

This library is really easy to use and highly recommended!

5. semver

#semver

is a npm library for semantic version management ; semver is used in vue3 framework source code and vite tool source code; To put it bluntly, you are developing an open source library When, you will definitely encounter situations where you need to remind users that different version numbers are different, so how to determine if the user version is too low,

semver

can help you solve this problem very well;

semver

has many built-in methods, such as judging whether a version is legal, judging whether the version number is named correctly, which of the two versions is bigger and which is smaller, etc. and other methods;

The following are examples from some official websites:

const semver = require('semver')

semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
semver.clean('  =v1.2.3   ') // '1.2.3'
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
semver.gt('1.2.3', '9.8.7') // false
semver.lt('1.2.3', '9.8.7') // true
semver.minVersion('>=1.0.0') // '1.0.0'
semver.valid(semver.coerce('v2')) // '2.0.0'
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
Copy after login
More usage methods

See the documentation for details

6. minimist

minimist 是一个命令行参数解析工具;minimistvue3 框架源码和 vite 工具源码中都有使用;

使用:

const args = require('minimist')(process.argv.slice(2))
Copy after login

例如:

# 执行以下命令
vite create app -x 3 -y 4 -n5 -abc --beep=boop foo bar baz

# 将获得
{ _: [ 'foo', 'bar', 'baz' ],
  x: 3,
  y: 4,
  n: 5,
  a: true,
  b: true,
  c: true,
  beep: 'boop' }
Copy after login

特别要说明的是返回值其中首个 key 是_,它的值是个数组,包含的是所有没有关联选项的参数。

如果你的工具在终端有较多的参数,那么这个工具就非常的适合您!

7. magic-string

magic-string 是一个用于操作字符串和生成源映射的小而快的库;

其实它最主要的功能就是对一些源代码和庞大的 AST 字符串做轻量级字符串的替换;

vite 工具源码和 @vue/compiler-sfc 中大量使用;

使用:

import MagicString from 'magic-string';
const s = new MagicString('problems = 99');

// 替换 problems -> answer
s.overwrite(0, 8, 'answer')
s.toString() // 'answer = 99'

// 生成 sourcemap
var map = s.generateMap({
  source: 'source.js',
  file: 'converted.js.map',
  includeContent: true
})
Copy after login

8. fs-extra

fs-extra 是一个强大的文件操作库, 是 Nodejs fs 模块 的增强版;

这个就不多讲了,因为它在千锤百炼之下只能形容它是 YYDS,查看 更多官方文档

9. chokidar

chokidar 是一款专门用于文件监控的库;chokidar 只在 vite 工具源码中有使用;

其实 Node.js 标准库中提供 fs.watchfs.watchFile 两个方法用于处理文件监控,但是为什么我们还需要chokidar 呢?

主要是由于 兼容性不好、无法监听、监听多次 等大量影响性能的问题;

chokidar 用法:

const chokidar = require('chokidar');

const watcher = chokidar.watch('file, dir, glob, or array', {
  ignored: /(^|[\/\\])\../,
  persistent: true
});

watcher
  .on('add', path => console.log(`File ${path} has been added`))
  .on('change', path => console.log(`File ${path} has been changed`))
  .on('unlink', path => console.log(`File ${path} has been removed`))
  .on('addDir', path => console.log(`Directory ${path} has been added`))
  .on('unlinkDir', path => console.log(`Directory ${path} has been removed`))
  .on('error', error => console.log(`Watcher error: ${error}`))
  .on('ready', () => console.log('Initial scan complete. Ready for changes'))
  .on('all', (event, path) => console.log(event,path))
  .on('raw', (event, path, details) => {
    log('Raw event info:', event, path, details);
  });
Copy after login

10. fast-glob

fast-glob 是一个快速批量导入、读取文件的库; fast-glob 只在 vite 工具源码中有使用;

基本语法:

  • * :匹配除斜杆、影藏文件外的所有文件内容;

  • **:匹配零个或多个层级的目录;

  • ?:匹配除斜杆以外的任何单个字符;

  • [seq]:匹配 [] 中的任意字符 seq;

如何使用:

const fg = require('fast-glob');

const entries = await fg(['.editorconfig', '**/index.js'], { dot: true });
Copy after login

vite 中使用:

vite 工具中 import.meta.glob 方法(如下)就是基于这个库来实现,所以如果你在自己的工具库中有批量文件等的操作,这个库是以很不错的选择;

const modules = import.meta.glob('./dir/*.js', { query: { foo: 'bar', bar: true } })
Copy after login

vite 通过 fast-glob 工具把它生成如下代码

// vite 生成的代码
const modules = {
  './dir/foo.js': () =>
    import('./dir/foo.js?foo=bar&bar=true').then((m) => m.setup),
  './dir/bar.js': () =>
    import('./dir/bar.js?foo=bar&bar=true').then((m) => m.setup)
}
Copy after login

11. debug

debug 是一个模仿 Node.js 核心调试技术的小型 JavaScript 调试程序,在适用于 Node.jsWeb 浏览器 都可使用;debug 只在 vite 工具源码中有使用;

说直白点就是你可以使用 debug 来对你的程序进行 毫秒级别时间差的统计 对你程序代码进行优化;

Understand Vue3+Vite3 source code in seconds, as long as you know these 20 libraries!

使用:

var debug = require('debug')('http')
  , http = require('http')
  , name = 'My App';

// fake app

debug('booting %o', name);

http.createServer(function(req, res){
  debug(req.method + ' ' + req.url);
  res.end('hello\n');
}).listen(3000, function(){
  debug('listening');
});

// fake worker of some kind

require('./worker');
Copy after login

如果你对你的代码或者自研的工具等有较高性能要求,强烈建议可以使用 debug 来进行调式。

12. dotenv

dotenv 是一个零依赖模块,可将 .env 文件 中的环境变量加载到 process.env 中;dotenv 只在 vite 工具源码中有使用;

如何使用:

1、创建 .env 文件

S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
Copy after login

2、使用

import * as dotenv from 'dotenv'
dotenv.config()
console.log(process.env)
Copy after login

13. esbuild

esbuild 是一个基于 Go 语言开发的 JavaScript 打包工具,被 Vite 用于开发环境的依赖解析;

相比传统的打包工具,主打性能优势,在构建速度上可以快 10~100 倍;

Understand Vue3+Vite3 source code in seconds, as long as you know these 20 libraries!

到现在知道为啥 vite 为啥快了吧,esbuild 就是第一功臣。

优势:

  • 没有缓存机制也有极快的打包速度
  • 支持es6和cjs模块
  • 支持es6 modules的tree-shaking
  • 支持ts和jsx
  • sourcemap
  • 压缩工具
  • 自定义的插件开发

使用:

esbuild 在 API 层面上非常简洁, 主要的 API 只有两个: TransformBuild, 这两个 API 可以通过 CLI, JavaScript, Go 的方式调用;

1、transform:调用这个API能将 tsjsx 等文件转换为js文件;

// cli
exbuild ./test.ts --loader=ts // 输出 const str = 'Hello World';

// js api调用
const esbuild = require('esbuild');
const fs = require('fs');
const path = require('path');
const filePath = path.resolve(__dirname, 'test.ts');
const code = esbuild.transformSync(fs.readFilesync(filePath), {
    loader: 'ts',
})
console.log(code);
// 输出
// {
//  code: 'const str = 'Hello World'',
//  map: '',
//  warnings: []
// }
Copy after login

2、build:整合了transform后的代码,可以将一个或者多个文件转换并保存为文件;

// cli
esbuild test.ts --outfile=./dist/test.js // { errors: [], warnings: [] }

// js api调用
const esbuild = require('esbuild');
const path = require('path');

const result = esbuild.buildSync({
  entryPoints: [path.resolve(__dirname, 'test.ts')],
  outdir: path.resolve(__dirname, 'dist'),
});

console.log(result); // { errors: [], warnings: [] }
Copy after login

更多详细使用可查看链接

14. rollup

rollup 是一个 JavaScript 模块打包器,可以将小块代码编译成大块复杂的代码,我们熟悉的 vue、react、vuex、vue-router 等都是用 rollup 进行打包的。

vite 中的生产环境(Production)  就是基于 rollup 打包来构建主要代码的。

使用:

1、创建 rollup.config.js 文件

2、配置文件

export default {
  input: 'src/index.js',
  output: {
    name: 'amapUpper',
    file: 'dist/amapUpper.js',
    format: 'umd'
  },
  plugins: []
};
Copy after login

3、运行

{
  "scripts": {
    "dev": "rollup -i src/index.js -o dist/bundle.js -f es"
  },
}
Copy after login

4、执行 npm run dev

15. ws

ws 是一个简单易用、速度极快且经过全面测试的 WebSocket 客户端服务器 实现;完全可以是 Socket.io 的替代方案;ws 只在 vite 工具源码中有使用。

说直白一点就是通过 ws,咱们可以实现服务端和客户端的长连接,且通过 ws 对象,就可以获取到 客户端发送过来的信息主动推送信息给客户端

使用:

1、server.js

    const WebSocket = require('ws')
    const WebSocketServer = WebSocket.Server;
    
    // 创建 websocket 服务器 监听在 3000 端口 
    const wss = new WebSocketServer({port: 3000}) 
    
    // 服务器被客户端连接 
    wss.on('connection', (ws) => { 
        // 通过 ws 对象,就可以获取到客户端发送过来的信息和主动推送信息给客户端 
        var i=0 
        var int = setInterval(function f() { 
            ws.send(i++) // 每隔 1 秒给连接方报一次数 
        }, 1000) 
    })
Copy after login

2、client.js

const WebSocket = require('ws')
const ws = new WebSocket('ws://localhost:3000')

// 接受
ws.on('message', (message) => {
  console.log(message)

    // 当数字达到 10 时,断开连接
    if (message == 10) {
      ws.send('close');
      ws.close()
  }
})
Copy after login

16. connect

connect 是一个最早期的 HTTP 服务器框架,亦可称为中间件插件;express 就是基于此框架做的扩展;

注意:从 vite2 开始官方已从依赖 koa 转成 connect 了;

至于为什么使用 connect 而不是 koa,咱们看官方的回答:

Understand Vue3+Vite3 source code in seconds, as long as you know these 20 libraries!

大概意思就是:由于大部分逻辑应该通过插件钩子而不是中间件来完成,因此对中间件的需求大大减少;所以使用 connect优先级会高于 Koa

17. esno

esno 是一个基于 esbuildTS/ESNextNode.js 运行时;

说直白点就是可以类似 ts-node 一样直接运行 TS 文件,那为甚么还用 esno 呢?

因为 esno 是基于 esbuild 运行的,esbuild 有多快,上面我们有讲到了吧,这里就不复述了。

使用:

{
  "scripts": {
    "start": "esno index.ts"
  },
  "dependencies": {
    "esno": "*"
  }
}
Copy after login
npm run start
Copy after login

18. tsup

tsup 是一个轻小且无需配置的,由 esbuild 支持的打包工具;

它可以直接把 .ts、.tsx 转成不同格式 esm、cjs、iife 的文件,快速打包你的工具库;

使用:

1、安装 tsup

pnpm i tsup -D
Copy after login

2、在根目录下的 package.json 中配置

{
  "scripts": {
    "dev": "pnpm run build -- --watch --ignore-watch examples",
    "build": "tsup src/index.ts --dts --format cjs,esm"
  },
}
Copy after login

19. vitepress

vitepress 是在 vuepress 的基础上实现的静态网站生成器,区别在于 vitepress 是建立在 vite 之上做的开发;

优势:

  • Based on vite instead of webpack, all faster startup times, hot reloads, etc;
  • uses vue3 To reduce the payload of js;

So if you want to write an online document warehouse, thenvitepress is a good choice.

20. vitest

vitest is a fast unit testing framework powered by vite.

Advantages:

  • Extremely fast unit testing framework powered by Vite ⚡️.

  • Common to Vite configuration, extremely fast response in watch mode (equivalent to HMR in test).

  • Vue/React components can be tested.

  • Use Typescript/JSX/ESM out of the box (I think people who have used jest should understand what this means)

  • With Jest has almost the same API, and also has Jest's snapshot function (this is very easy to use!)

  • Simulate DOM

  • Generate test coverage

  • ESM first, top level waiting

  • TypeScript/JSX support out of the box

  • Kit And test filtering, timeout, concurrency

  • etc

So what reason do you have for not usingvitest Woolen cloth?

Others

In fact, careful students may find that currently vue3 and vite3 are both a monorepo Warehouse, and all use pnpm workspace for warehouse management;

So understand monorepo and pnpm workspace and read the source code. Very helpful;

For more details about this, you can check "How to Get Started with Vite Source Code" to learn more.

https://juejin.cn/post/7094984070999834655

Of course, the tool libraries shared above are only libraries that use many scenarios in the source code , there are also some libraries that have fewer scenarios, so there is no detailed explanation here. If you want to know which tool library in the source code, you are welcome to add it. I will update it in time after making the choice;

Original address: https://juejin.cn/post/7124112069355372581

Author: Master Yi

prompts
vue3 197 kB 13,292,137
Other 87.7 kB 24,793,335
Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!