vite.config.js配置详解

发布时间 2023-10-27 18:28:14作者: 苏格是只猫
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
 
export default defineConfig({
    // 根路径,也就是项目的基础路径
    base: '/',
    // 服务器配置
    server: {
        // 服务器主机名,默认是 localhost
        host: 'localhost',
        // 端口号,默认是 5173
        port: 8081,
        // 是否开启 https
        https: false,
        // 服务器代理配置
        // proxy: {
        //     // 如果请求的路径符合该正则表达式,则会被代理到 target 中
        //     // 例如请求 /api/user 会被代理到 http://localhost:8888/api/user
        //     '^/api': {
        //         target: 'http://localhost:8888',
        //         changeOrigin: true,
        //         rewrite: (path) => path.replace(/^\/api/, ''),
        //     },
        // },
        // 自定义中间件
        middleware: [],
        // 是否开启自动刷新
        // hmr: true,
        // 是否开启自动打开浏览器
        open: true,
 
    },
    // 构建配置
    build: {
        // 输出目录,默认是 dist
        outDir: 'dist',
        // 是否开启 sourcemap
        sourcemap: false,
        // 是否开启压缩
        minify: 'terser', // 可选值:'terser' | 'esbuild'
        // 是否开启 brotli 压缩
        brotli: true,
        // 是否将模块提取到单独的 chunk 中,默认是 true
        chunkSizeWarningLimit: 500,
        // 是否提取 CSS 到单独的文件中
        cssCodeSplit: true,
        // 是否开启 CSS 压缩
        cssMinify: true,
        // 是否开启 CSS 去重
        cssInlineLimit: 4096,
        // 启用/禁用 esbuild 的 minification,如果设置为 false 则使用 Terser 进行 minification
        target: 'es2018', // 可选值:'esnext' | 'es2020' | 'es2019' | 'es2018' | 'es2017' | 'es2016' | 'es2015' | 'es5'
        // 是否开启 Rollup 的代码拆分功能
        rollupOptions: {
            output: {
                manualChunks: {},
            },
        },
        // 是否开启增量式构建
        // https://vitejs.dev/guide/build.html#incremental-build
        incremental: false,
    },
    // 这个resolve是node_modules中的path里面的pash.js提供的一个解析路径的方法,他总是返回一个以相对于当前的工作目录的绝对路径。
    resolve: {
        // ↓路径别名,主要是这部分
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    },
    // 插件配置
    plugins: [vue()],
    // 环境变量配置
    define: {
        'process.env': {},
    },
    // 优化配置
    optimizeDeps: {
        // 是否将 Vue、React、@vueuse/core 和 @vueuse/head 作为外部依赖提取出来
        include: ['vue', 'react', '@vueuse/core', '@vueuse/head'],
        // 是否开启预构建,将预构建后的代码提前注入到浏览器缓存中,以减少首次加载的时间
        prebuild: false,
    },
});