vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vite配置文件vite.config.js

一文彻底搞懂Vite配置文件vite.config.js

作者:编程随想_Code

这篇文章主要介绍了Vite配置文件vite.config.js的相关资料,这个vite.config.js文件是Vite项目的核心配置文件,它使用导出一个配置对象来定制Vite的行为,需要的朋友可以参考下

一、vite.config.js 是什么?

在使用 Vite 进行前端开发时,我们通常会在项目根目录下看到一个 vite.config.js 文件(也可以是 vite.config.ts)。

这个文件的作用类似于 webpack 的 webpack.config.js,用于对 Vite 的行为进行个性化配置,比如:

Vite 默认情况下已经足够开箱即用,但在真实的项目开发中,我们通常需要通过配置文件来适配不同的业务需求。

二、vite.config.js 的基本结构

vite.config.js 本质上就是一个 配置对象,它通过 defineConfig 方法导出,写法如下:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  server: {
    port: 3000,
    open: true
  },
  resolve: {
    alias: {
      '@': '/src'
    }
  }
})

解释:

三、常见配置项详解

1. 基础配置

export default defineConfig({
  base: './', // 部署应用的基础路径,默认是 '/'
  root: './', // 项目根目录,默认就是当前目录
})

2. 开发服务器 server

server: {
  host: '0.0.0.0', // 允许局域网访问
  port: 5173,      // 默认端口
  open: true,      // 是否自动打开浏览器
  proxy: {         // 配置反向代理
    '/api': {
      target: 'http://localhost:8080',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/api/, '')
    }
  }
}

3. 路径别名 resolve

resolve: {
  alias: {
    '@': '/src',
    'components': '/src/components'
  }
}

这样我们在引入文件时可以简化路径:

import Header from '@/components/Header.vue'

4. 插件 plugins

Vite 的强大之处在于它的插件系统。
比如 Vue 项目通常需要:

import vue from '@vitejs/plugin-vue'
plugins: [vue()]

React 项目则需要:

import react from '@vitejs/plugin-react'
plugins: [react()]

5. 构建配置 build

build: {
  outDir: 'dist',     // 打包目录
  sourcemap: false,   // 是否生成 source map
  minify: 'esbuild',  // 压缩方式(esbuild 或 terser)
  rollupOptions: {
    output: {
      manualChunks: {
        vue: ['vue'], // 单独打包 vue 相关依赖
      }
    }
  }
}

6. 环境变量与模式

Vite 默认支持 .env 文件,我们可以在配置文件中根据环境区分逻辑:

export default defineConfig(({ mode }) => {
  console.log('当前模式:', mode) // development / production
  return {
    base: mode === 'production' ? '/prod/' : '/'
  }
})

四、完整示例

下面给一个常用的 vite.config.js 配置示例:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig(({ mode }) => {
  return {
    base: mode === 'production' ? '/my-app/' : '/',
    plugins: [vue()],
    server: {
      host: '0.0.0.0',
      port: 3000,
      open: true,
      proxy: {
        '/api': {
          target: 'http://localhost:8080',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        }
      }
    },
    resolve: {
      alias: {
        '@': '/src'
      }
    },
    build: {
      outDir: 'dist',
      sourcemap: false,
      rollupOptions: {
        output: {
          manualChunks: {
            vue: ['vue']
          }
        }
      }
    }
  }
})

五、总结

如果你之前是用 webpack 的,可能会觉得 Vite 的配置简洁得多,这也是 Vite 能够快速流行的原因之一。

到此这篇关于Vite配置文件vite.config.js的文章就介绍到这了,更多相关Vite配置文件vite.config.js内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文