VUE2 中使用 Webpack 打包、开发,每次打包时间太久,尤其是在开发的过程中,本文记录一下 VUE2 升级Vite 步骤。
安装 Vue2 Vite 依赖
dev 依赖
@vitejs/plugin-vue2": "^2.3.3
@vitejs/plugin-vue2-jsx": "^1.1.1
vite": "^5.0.0
#选装,自动添加后缀
vite-plugin-resolve": "^2.5.2
npm 脚本
"scripts": {"dev": "vite","build": "vite build","serve": "vite preview"},
viteconfigjs_20">vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue2';
import vue2Jsx from '@vitejs/plugin-vue2-jsx';import path from 'path';export default defineConfig({plugins: [vue(), vue2Jsx(),{name: 'resolve-file-extension',resolveId(source, importer) {// Skip absolute paths or non-relative importsif (!importer || !source.startsWith('.') || source.includes('?')) {return null;}const extensions = ['.vue', '.js', '.ts', '.jsx', '.tsx']; // Add supported extensionsfor (const ext of extensions) {try {const resolvedPath = require.resolve(source + ext, { paths: [importer] });return resolvedPath;} catch (e) {continue;}}return null;},},],resolve: {extensions: ['.vue', '.js', '.jsx', '.ts', '.tsx'],alias: {'@': path.resolve(__dirname, './src'), // Alias `@` to `src` directory},},server: {host: '0.0.0.0',port: 8080,open: true,proxy: {'/api': {target: 'http://localhost:8090/', // Target server for `/api` requestsrewrite: (path) => path.replace(/^\/api/, '/'), // Remove `/api` prefixchangeOrigin: true, // Handle CORS},},},css: {preprocessorOptions: {less: {modifyVars: {// Uncomment and define your custom LESS variables here// "primary-color": "#377DF6",// "link-color": "#377DF6",},javascriptEnabled: true, // Enable JavaScript in LESS},},},build: {sourcemap: process.env.NODE_ENV === 'development', // Source maps for development},
});
index.html
将 Index.html 从 public 移动到根目录下,与 webpack 相关的去掉。
<!DOCTYPE html>
<html lang=""><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1.0"><link rel="icon" href="./favicon.ico"><title>TestTTT</title>
</head><body><noscript><strong>We're sorry,work properly without JavaScript enabled.Please enable it to continue.</strong></noscript><div id="app"></div><script type="module" src="/src/main.js"></script><!-- built files will be auto injected -->
</body></html>
jsx
如果你的项目中使用了 jsx,需要在 script 中制定 lang="jsx"
<script lang="jsx">
export default {props:["title", "open", "label"],data() {return {}},
}
</script>
总结
Vue2 升级 Vite 比较顺利,几点要注意的:
- 用 Vite 5.0,jsx 插件只支持到 Vite 5.0
- Webpack 语法要移除
- 其他遇到问题,让豆包把代码修改为 Vite 方式即可