本文是在 vite 官方文档教程:https://cn.vitejs.dev/ 基础上,学习整理而来。
接下来我将通过对比 create-react-app 或 webpack 的形式来学习 vite。
vite 的目标就是构建适用于现代浏览器,根本不考虑旧版浏览器,例如 IE 11 等。
并且 vite 支持编译目标 JS 的版本最低为 ES2015。
所以如果你的项目需要适配旧的浏览器,那么建议你别使用 vite,还继续使用 webpack 吧。
当然你也可以选择安装使用 @vitejs/plugin-legacy
这个插件,用来适配到旧版浏览器。
创建一个 React 项目:
//创建 React 项目
- yarn create react-app xxx+ yarn create vite xxx --template react//创建 React + TypeScript 项目
- yarn create react-app xxx --template typescript+ yarn create vite xxx --template react-ts
创建一个 Vue 项目:
//创建 Vue 项目
yarn create vite xxx vue
//创建 Vue + TypeScript 项目
yarn create vite xxx --template vue-ts
针对 React + TypeScript 的注意事项:
由于最新版 vite react-ts 模板中使用的 TypeScript 版本为 5+,因此需要比较新的 VSCode 才可以支持。
准确来说需要的是 VSCode 1.77 以上的版本才可以支持到 TS 5+,如果你的 VSCode 版本低于此版本,那么由于对 TS 5+ 的不支持,你会收到一些莫名其妙的错误警告,例如:
Module '"xxxx/node_modules/@types/react/index"' can only be default-imported using the 'allowSyntheticDefaultImports' flag
如果你真的不方便升级 VSCode (不建议),那么你需要修改 tsconfig.json
- "moduleResolution": "bundler",+ "moduleResolution": "node",- "allowImportingTsExtensions": true,
安装其他框架:
vite 除了 react 或 vue 外还支持其他众多框架,可以执行: