Skip to content

Vite 配置文件

ts
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { fileURLToPath } from 'url'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

function resolvePath(paths: string) {
  return path.resolve(__dirname, paths)
}

export default defineConfig(({ mode }) => {
  const root = process.cwd()
  const env = loadEnv(mode, root)

  return {
    base: env.VITE_BASE_URL,
    server: {
      port: env.VITE_PORT,
      host: true,
      // 本地跨域代理
      // proxy: {
      //   '/api': {
      //     target: VITE_API_PROXY_URL,
      //     changeOrigin: true
      //   }
      // }
    },
    resolve: {
      // 路径别名
      alias: { 
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@views': resolvePath('src/views')
      },
    },
    build: {
      target: 'es2015',
      outDir: 'dist',
      chunkSizeWarningLimit: 2000,
      minify: 'terser',
      terserOptions: {
        compress: {
          // 生产环境去除 console
          drop_console: true,
          // 生产环境去除 debugger
          drop_debugger: true
        }
      },
      dynamicImportVarsOptions: {
        warnOnError: true,
        exclude: [],
        include: ['src/views/**/*.vue']
      }
    },
    plugins: [
      vue(),
      // 自动按需导入 API
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      // 自动按需导入组件
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    // 依赖预构建
    optimizeDeps: {
      include: [],
      exclude: []
    },
    css: {
      preprocessorOptions: {
        scss: {
          // 每个 Sass 文件都会自动引入
          additionalData: `@use "@/styles/variables.scss"`
        }
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              }
            }
          }
        ]
      }
    }
  }
})

如有转载请标注本站地址