vite.config.js常用配置

Vite

Vite,是一种新型的前端开发与构建工具。它是一个开发服务器,它基于原生ES 模块提供了丰富的内建功能,如速度快到惊人的模块热更新(HMR)。

中文文档

为什么选Vite

优点:

  1. 极速的服务启动,不需要等待打包操作;
  2. 轻量快速的热重载,无论应用程序大小如何,都始终极快的模块热重载(HMR);
  3. 优化的构建,按需编译,不再等待整个应用编译完成;
  4. 丰富的功能,对 TypeScript、JSX、CSS 等支持开箱即用;
  5. 通用的插件,完全类型化的API。

环境配置

新建.env.production文件,内容如下:

# 环境模式
VITE_APP_MODE = production
VITE_APP_ENV = production

新建.env.test文件,内容如下:

# 环境模式
VITE_APP_MODE = test
VITE_APP_ENV = production

修改package.json文件

{
    
    
  "scripts": {
    
    
    "dev": "vite",
    "test": "vite build --mode test",
    "build": "vite build --mode production"
  },
}

常用配置

import {
    
     defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import legacy from '@vitejs/plugin-legacy'
import path from 'path'

const resolve = str => path.resolve(__dirname, str)

export default defineConfig(({
     
      mode }) => {
    
    
  const ENV = loadEnv(mode, __dirname)
  const IS_DEV = ENV.VITE_APP_ENV !== 'production'

  return {
    
    
	  base: './',
	  resolve: {
    
    
	    alias: {
    
    
	      '@': resolve('src')
	    },
	    extensions: ['.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
	  },
	  build: {
    
    
	    // 打包构建输出路径
	    outDir: 'dist',
	     // 生成静态资源的存放路径
	     assetsDir: 'static',
	     // 构建后是否生成 source map 文件
	     sourcemap: IS_DEV,
	     // chunk 大小警告的限制
	     chunkSizeWarningLimit: 700,
	     // 生产环境移除 console
	     minify: 'terser',
	     terserOptions: {
    
    
	       compress: {
    
    
	         drop_console: !IS_DEV,
	         drop_debugger: !IS_DEV
	       }
	     },
	    rollupOptions: {
    
    
	      output: {
    
    
	        // https://rollupjs.org/guide/en/#outputmanualchunks
	        manualChunks: {
    
    
	          vlib: ['vue', 'vue-router', 'vuex']
	        }
	      }
	    }
	  },
	  server: {
    
    
	    port: 8088,
	    open: true,
	    proxy: {
    
    
	      '/api': 'http://127.0.0.1:3000'
	    },
	    cors: true
	  },
	   css: {
    
    
	    // 处理打包出现警告 "@charset" must be the first
	    postcss: {
    
    
	      plugins: [
	        {
    
    
	          postcssPlugin: 'internal:charset-removal',
	          AtRule: {
    
    
	            charset: atRule => {
    
    
	              if (atRule.name === 'charset') {
    
    
	                atRule.remove()
	              }
	            }
	          }
	        }
	      ]
	    }
	  },
	  plugins: [
	    vue(),
	    vueJsx(),
	    legacy()
	  ],
  }
})

猜你喜欢

转载自blog.csdn.net/kiscon/article/details/118256611
今日推荐