Vite对比VueCLI

开发服务器架构对比

与Vue CLI类似,Vite也是一个提供基本项目脚手架和开发服务器的构建工具。 然而,Vite并不是基于Webpack的,它有自己的开发服务器,利用浏览器中的原生ES模块。这种架构使得Vite比Webpack的开发服务器快了好几个数量级。Vite采用Rollup进行构建,速度也更快。

Vite开发服务器架构

Vite不捆绑应用服务器端。相反,它依赖于浏览器对JavaScript模块的原生支持(也就是ES模块,是一个比较新的功能)。 浏览器将在需要时通过HTTP请求任何JS模块,并在运行时进行处理。Vite开发服务器将按需转换任何文件(如Sass、TypeScript、SFC)。 这种架构避免了服务器端对整个应用的捆绑,并利用浏览器高效的模块处理,提供了一个明显更快的开发服务器。

Webpack开发服务器架构

Webpack的工作方式是,它通过解析应用程序中的每一个 import 和 require ,将整个应用程序构建成一个基于JavaScript的捆绑包,并在运行时转换文件(例如Sass、TypeScript、SFC)。 这都是在服务器端完成的,依赖的数量和改变后构建/重新构建的时间之间有一个大致的线性关系。

提示:当你对应用程序进行code-split和tree-shake动时,Vite的速度会更快,因为它只加载它需要的模块,即使是在开发阶段。这与Webpack不同,在Webpack中,代码拆分只对生产包有利。

创建Vue3工程

本文使用的是yarn作为包管理器

1
2
# 全局安装yarn包管理器
npm install -g @yarn

Vite

Vite官网:https://cn.vitejs.dev/guide/

命令行输入以下命令:

1
2
3
4
5
6
7
8
9
10
# 创建Vue3+TS工程
yarn create vite my-vue-app --template vue-ts
# 安装Vue Router 4: https://next.router.vuejs.org/zh/introduction.html
yarn add vue-router@4 -S
# 安装Vuex 4: https://next.vuex.vuejs.org/zh/index.html
yarn add vuex@next -S
# 安装Element Plus: https://element-plus.org/zh-CN/guide/design.html
yarn add element-plus -S
# 运行
yarn run dev

Vue CLI

Vue CLI官网: https://cli.vuejs.org/zh/

Vue CLI创建工程前需要全局安装的模块

1
2
3
4
# Vue CLI脚手架
npm install -g @vue/cli
# 用于Vue编译,防止报错
npm install -g vue-template-compiler

命令行输入以下命令:

1
2
3
4
# 创建Vue3+TS工程
vue create vue3-ts
# 运行
yarn serve

搭建过程中的相关设置,可根据自己的实际情况设置

配置

  • Manually select features // 手动选择
  • Check the features needed for your project: // 选择我们所需的选项来生成项目,上下箭头选择,使用空格键选中,回车确认
  • Choose a version of Vue.js that you want to start the project with // 选择 Vue 版本
  • Use class-style component syntax? (Y/n) // 是否使用 Class(类)风格装饰器, 即通过 export default class Home extends Vue{} 创建 Vue 实例
  • Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? (Y/n) // 使用 Babel 做转义, 与 TypeScript 一起用于自动检测
  • Use history mode for router? // 路由模式, 是否选择 history 模式
  • Pick a CSS pre-processor? // 选择一种 css 预处理器
  • Pick a linter / formatter config? // 选择一种代码格式化检测工具
  • Pick additional lint features? // 代码检查方式: 保存时检查 or 提交时检查
  • Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? // Babel, PostCSS, ESLin 等配置文件怎么存放, 是放到单独的配置文件中?还是 package.json 里?
  • Save this as a preset for future projects? // 是否需要保存当前配置,在以后的项目中可快速构建?
  • Pick the package manager to use when installing dependencies: // 选择包管理器