vite.config.js 配置及优化

221 阅读1分钟

基础环境

  • vite版本:4+
  • 项目框架:vue 3
  • UI框架:Ant-Design-Vue
  • 开发语言:TypeScript
import { fileURLToPath, URL } from 'node:url'
import { resolve } from 'path'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { defineConfig, loadEnv } from 'vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'

const pathResolve = (dir: string): string => {
  return resolve(__dirname, '.', dir)
}

// https://vitejs.dev/config/
export default defineConfig((command: any, mode: string) => {
  const env = loadEnv(mode, process.cwd(), '')

  return {
    plugins: [
      vue(),
      vueJsx(),
      Components({
        resolvers: [AntDesignVueResolver({ importStyle: 'less' })]
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    base: '/evalweb/', // 开发或生产环境服务的公共基础路径
    server: {
      https: false,
      port: 8000,
      host: '0.0.0.0',
      proxy: {}
    },
    build: {
      outDir: 'evalweb', // 输出路径
      sourcemap: false, // 是否生成 source map 文件, https://cn.vitejs.dev/config/build-options.html#build-sourcemap
      chunkSizeWarningLimit: 1500, // 触发警告的 chunk 大小
      assetsInlineLimit: 1024 * 5, // 小于此阈值的导入或引用资源将内联为 base64 编码,以避免额外的 http 请求。默认:4kb
      modulePreload: {
        polyfill: true // 预加载
      },
      cssCodeSplit: true, // 拆分 CSS 代码
      rollupOptions: {
        input: {
          index: pathResolve('index.html')
        },
        // 指定生成的 chunk 被放置在哪个目录中,这里指定在 static/js/ 下,hash 值长度为10
        output: {
          chunkFileNames: 'static/js/[name]-[hash:10].js', // 自定义命名代码分割中产生的 chunk 
          entryFileNames: 'static/js/[name]-[hash:10].js', // 指定 chunks 的入口文件模式
          assetFileNames: 'static/[ext]/[name]-[hash:10].[ext]' // 自定义构建结果中的静态资源名称
        }
      }
    },
    css: {
      preprocessorOptions: {
        less: {
          // 修改 ant-design 主题及样式
          modifyVars: {
            hack: `true; @import '@/style/ant-design.less'; @import '@/style/canon-color.less'; @import '@/style/mixin.less';`
          },
          javascriptEnabled: true
        }
      }
    }
  }
})