vite.config.js配置大全
时间: 2025-02-23 15:24:15 浏览: 100
### 关于 `vite.config.js` 的全面配置指南
#### 文件位置与命名
在项目的根目录下创建一个名为 `vite.config.js` 或者如果倾向于使用 TypeScript,则可以命名为 `vite.config.ts`。这个文件的作用在于让开发者能够自定义 Vite 构建工具的行为,从而更好地适应不同的开发需求[^3]。
#### 基础配置属性
##### mode 和 define
- **mode**: 设置环境模式(development, production),这会影响最终打包的结果。
- **define**: 替换全局变量,在生产环境中通常用来移除调试语句等。
```javascript
export default {
mode: process.env.NODE_ENV,
define: {
'process.env': {}
}
}
```
#### 输入输出路径设置
##### root
指定站点的根目录,默认为当前工作目录(`.`),可以通过此参数调整到其他子目录作为新的起点。
##### base
当部署至非根域名时非常有用,比如 GitHub Pages 这样的平台,它允许设定相对 URL 路径前缀来确保资源加载正确无误。
```javascript
import { fileURLToPath } from 'url';
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default {
root: './src',
base: '/my-project/',
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
}
};
```
#### 插件管理
通过 plugins 数组引入各种功能增强型插件,这些插件可以帮助处理 CSS、图片优化等问题,极大地方便了前端工程化流程中的诸多环节[^2]。
```javascript
import vue from '@vitejs/plugin-vue';
import legacy from '@vitejs/plugin-legacy';
export default {
plugins: [
vue(),
legacy({
targets: ['defaults', 'not IE 11']
})
]
};
```
#### 开发服务器选项(server)
提供了一系列有关本地服务端口、代理转发等方面的定制能力,使得测试阶段更加灵活多变。
```javascript
server: {
port: 8080,
open: true,
proxy: {
'/api': 'http://localhost:3000'
}
},
```
#### 打包构建(build)
控制着最终产物的形式以及一些性能调优措施,如压缩混淆代码、分离CSS文件成独立实体等等。
```javascript
build: {
outDir: 'dist',
assetsInlineLimit: 4096,
rollupOptions: {
output: {
chunkFileNames: 'static/js/[name]-[hash].js',
entryFileNames: 'static/js/[name]-[hash].js',
assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
}
},
terserOptions: {
compress: {
drop_console: true
}
}
}
```
#### 别名解析(resolve.alias)
简化模块导入路径书写方式,提高可读性和维护效率的同时减少错误发生的几率。
```javascript
resolve: {
alias: {
'@components': path.resolve(__dirname, 'src/components'),
'@utils': path.resolve(__dirname, 'src/utils')
}
}
```
#### 类型声明(types)
对于采用TypeScript语言书写的项目而言尤为重要,这里指定了类型定义的位置以便编辑器能识别并给出提示。
```typescript
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
```
以上就是围绕 `vite.config.js` 展开的一系列重要配置项及其应用场景实例展示,当然实际应用过程中还会有更多个性化的需求等待探索发现。
阅读全文
相关推荐


















