1. 處理依賴
yarn add vite vite-plugin-html @vitejs/plugin-vue -D
# 如果使用了jsx語法還需要
yarn add @vitejs/plugin-vue-jsx
# 如果需要生成d.ts文件
yarn add vite-plugin-dts -D
# 如果需要 analyzer
yarn add rollup-plugin-bundle-analyzer -D
刪除 webpack 依賴,常見的有
{
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-plugin-router": "~5.0.0",
"@vue/cli-plugin-typescript": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"@vue/eslint-config-typescript": "^9.1.0",
"vue-cli-plugin-style-resources-loader": "^0.1.5",
"webpack-cli": "^5.0.1"
}
2. 修改配置
// package.json
"type": "module",
"scripts": {
"serve": "vite --host 0.0.0.0 --port 8080",
"build": "vite build"
},
<!-- index.html -->
<script type="module" src="/src/main.ts"></script>
添加或修改
tsconfig.json
和tsconfig.node.json
先改,兩個文件參考 vite 項目.prettierrc.js
等配置文件后綴名改為 cjs-
刪除
vue.config.js
疚察,添加vite.config.ts
// vite.config.ts import { resolve } from 'path'; import { defineConfig } from 'vite'; import { createHtmlPlugin } from 'vite-plugin-html'; import vue from '@vitejs/plugin-vue'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [ vue(), createHtmlPlugin({ inject: { // 可以向html中注入變量,原來的 htmlWebpackPlugin.options.. 不能再用 }, }), // bundleAnalyzer(), // dts() ], resolve: { alias: { '@': resolve(__dirname, 'src'), }, // extensions: ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.cjs', '.vue'] }, css: { // css全局變量仇奶,如果需要的話 preprocessorOptions: { scss: { sourceMap: true, additionalData: `@import './src/styles/variables.scss';`, }, }, }, });
3. 代碼變更
process.env
換為import.meta.env
處理html中插入的變量
靜態(tài)資源引用
@/assets/xx.png
=>require('@/assets/xx.png')
-
添加
vite-env.d.ts
/// <reference types="vite/client" /> declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<{}, {}, any> export default component } interface ImportMetaEnv { readonly VITE_APP_TITLE: string // 更多環(huán)境變量... } interface ImportMeta { readonly env: ImportMetaEnv }
其它根據(jù)錯誤提示修改岛抄,比如有 jsx 語法的 vue 文件,要在 script 標簽上添加lang="jsx"
3.1 生成dts
vite-plugin-dts 與 jsx 一起使用時會報錯
tsc命令也可以生成dts
3.2 webpackChunkName
import(/* webpackChunkName: "xxx" */ ...
可以使用vite-plugin-webpackchunkname
來識別
3.3 workbox-webpack-plugin
使用插件vite-plugin-pwa
代替
3.4 worker-loader
vite自帶worker識別
3.5 CDN
Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".
借助vite-plugin-cdn-import
或rollup-plugin-external-globals
解決狈茉,詳見
https://juejin.cn/post/7115215444671201310
https://juejin.cn/post/7197222701220053047夫椭、https://juejin.cn/post/7233220422241108023