Skip to content

Vite

默认配置

ts
// vite
import { defineConfig } from 'vite';
// 导入vue
import vue from '@vitejs/plugin-vue';
// vue调试工具
import vueDevTools from 'vite-plugin-vue-devtools';
// element按需引入
import AutoImport from 'unplugin-auto-import/vite';
// 自动注册全局组件
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

// 路径模块(1)
// import { resolve } from "path";

// 路径导入以及url(2)
import { fileURLToPath, URL } from 'node:url';

export default defineConfig(({ mode })=>({
  base: "./",
  resolve: {
    alias: {
      // "@": resolve(__dirname, "./src"),
      // comp: resolve(__dirname, "./src/components"),

      '@': fileURLToPath(new URL('./src', import.meta.url)),
      'comp': fileURLToPath(new URL('./src/components', import.meta.url)),
    },
  },
  plugins: [
    vue(),
    // vue调试工具 【只开发环境使用】
    mode === 'development' ? vueDevTools() : undefined,
    // element按需引入
    AutoImport({
      resolvers: [ElementPlusResolver()],
      // 生成的类型文件路径(会自动创建,TS会识别)
      // dts: 'src/auto-imports.d.ts',
    }),
    Components({
      resolvers: [ElementPlusResolver()],
      // 生成的组件类型文件路径
      // dts: 'src/components.d.ts',

      // 方法1:明确指定只扫描哪些目录
      dirs: ["src/components/base"], // 只自动注册 `src/components/base`下的组件
      // 方法2:使用排除规则(正则表达式)
      // exclude: [
      //   /TopNavigation\.vue/, // 排除 TopNavigation 组件
      //   /loading\index\.vue/,       // 排除 Loading 组件
      //   /Progress\.vue/,       // 排除 progress 组件
      // ],
    }),
  ],
  
  // 生产构建设置
  build: {
    rollupOptions: {
      // 打包输出配置
      output: {
        /********** 使用 contenthash,确保只有内容变化的文件指纹才变 **********/
        // 1. 入口文件:使用 contenthash,8位长度通常足够且兼顾文件名长度
        entryFileNames: 'assets/[name]-[hash:16].js',

        // 2. 动态导入的 chunk(即你的各个页面):独立计算 contenthash
        chunkFileNames: 'assets/[name]-[hash:16].js',

        // 3. 静态资源(CSS、图片等):同样使用 contenthash
        assetFileNames: 'assets/[name]-[hash:16][extname]',

        // 分包
        manualChunks: (id)=> {
          // 把第三方依赖进行分包处理
          if (id.includes('node_modules') && (id.endsWith('.js') || id.endsWith('.ts'))) {
            return 'vendor';
          }
        }
      }
    }
  },
  
  server: {
    // 自动打开浏览器进行预览
    open: false,
    // 网络端口号
    port: 9999,
    host: "0.0.0.0",
    // 配置反向代理
    proxy: {
      "/api": {
        target: "http://localhost:3000",
        // target就是你要访问的目标地址,可以是基础地址,这样方便在这个网站的其他api口调用数据
        ws: true, //是否代理 websockets
        secure: false, //是否https接口
        changeOrigin: true, //是否跨域
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
      "/apiOne": {
        target: "http://luke.svvs.top",
        // target就是你要访问的目标地址,可以是基础地址,这样方便在这个网站的其他api口调用数据
        ws: true, //是否代理 websockets
        secure: false, //是否https接口
        changeOrigin: true, //是否跨域
        rewrite: (path) => path.replace(/^\/apiOne/, ""),
      },
    },
  },
}));

Copyright © 2026 Luke