前言
我们在搭建vue3项目的时候不可避免的会遇到“代理”、“端口”、“打包名”、“图片压缩”等配置问题,本文逐一讲述该怎么样在vite.config.js中去配置。
一、配置代理端口和代理转发
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ server: { host: 'localhost', port: 8080, // 端口 proxy: { '/api': { // 请求接口中要替换的标识 target: 'http://117.62.22.235:17009', // 代理地址 changeOrigin: true, // 是否允许跨域 secure: true, rewrite: (path) => path.replace(/^\/api/, '') // api标志替换为'' } } }, plugins: [vue()] })
复制
二、修改打包名
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], build: { outDir: 'distBigScreenBase' // 打包文件的输出目录 } })
复制
三、使用@
vite.config.ts添加如下代码
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from "path"; export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': resolve(__dirname, './src') } } })
复制
ts.config.json添加如下代码
{ "compilerOptions": { "paths": { "@/*": ["src/*"] } } }
复制
四、图片压缩
图片压缩先要引入vite-plugin-imagemin插件
命令:npm i vite-plugin-imagemin -D
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import viteImagemin from 'vite-plugin-imagemin' export default defineConfig({ plugins: [vue(), // 图片压缩 viteImagemin({ gifsicle: { optimizationLevel: 7, interlaced: false }, optipng: { optimizationLevel: 7 }, mozjpeg: { quality: 20 }, pngquant: { quality: [0.8, 0.9], speed: 4 }, svgo: { plugins: [ { name: 'removeViewBox' }, { name: 'removeEmptyAttrs', active: false } ] } }) ] })
复制
五、完整代码
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from "path"; import viteImagemin from 'vite-plugin-imagemin' export default defineConfig({ server: { host: 'localhost', port: 8080, proxy: { '/api': { // 请求接口中要替换的标识 target: 'http://117.62.22.235:17009', // 代理地址 changeOrigin: true, // 是否允许跨域 secure: true, rewrite: (path) => path.replace(/^\/api/, '') } } }, plugins: [vue(), // 图片压缩 viteImagemin({ gifsicle: { optimizationLevel: 7, interlaced: false }, optipng: { optimizationLevel: 7 }, mozjpeg: { quality: 20 }, pngquant: { quality: [0.8, 0.9], speed: 4 }, svgo: { plugins: [ { name: 'removeViewBox' }, { name: 'removeEmptyAttrs', active: false } ] } }) ], build: { outDir: 'distBigScreenBase' // 打包文件的输出目录 }, resolve: { alias: { '@': resolve(__dirname, './src') } } })
复制
总结
vue3的配置和vue2有所不同,不能照搬照套vue2,那样会报错。代码可以直接copy,亲测有效,只需要修改成自己想要的文件名、路径即可。