编辑
2024-10-31
前端
00
请注意,本文编写于 191 天前,最后修改于 191 天前,其中某些信息可能已经过时。

目录

1. plugins
2. resolve.alias
3. server
4. build
5. css
6. optimizeDeps
7. define
8. base
9. esbuild
10. assetsInclude

今天记录一下vite.config.js配置文件的学习,,每次有点问题就要去查(百度),然后复制粘贴,最近好好学习一下

1. plugins

用于配置 Vite 插件。通常情况下,你会使用 @vitejs/plugin-react 来支持 React。

ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], });

2. resolve.alias

用于配置路径别名,方便在代码中使用相对路径。

ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import path from 'path'; export default defineConfig({ plugins: [react()], resolve: { alias: { '@': path.resolve(__dirname, 'src'), }, }, });

3. server

用于配置开发服务器的行为。

ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], server: { port: 3000, // 指定开发服务器的端口 open: true, // 启动开发服务器时自动打开浏览器 proxy: { '/api': { target: 'http://localhost:5000', // 代理API请求到后端服务器 changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ''), }, }, }, });

4. build

用于配置构建选项。

ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], build: { outDir: 'dist', // 指定构建输出目录 assetsDir: 'assets', // 指定静态资源输出目录 sourcemap: true, // 生成 source map 文件 minify: 'esbuild', // 使用 esbuild 进行代码压缩 }, });

5. css

用于配置 CSS 相关选项。

ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], css: { preprocessorOptions: { scss: { additionalData: `@import "./src/styles/variables.scss";`, // 在每个 SCSS 文件中自动引入变量文件 }, }, }, });

6. optimizeDeps

用于配置依赖优化选项。

ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], optimizeDeps: { include: ['react', 'react-dom'], // 指定需要优化的依赖 }, });

7. define

用于定义全局常量。

ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), }, });

8. base

用于配置应用的公共基础路径。

ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], base: '/my-app/', // 指定应用的公共基础路径 });

9. esbuild

用于配置 esbuild 选项。

ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], esbuild: { jsxInject: `import React from 'react'`, // 自动注入 React import }, });

10. assetsInclude

用于配置静态资源包含规则。

ts
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], assetsInclude: ['**/*.svg', '**/*.png'], // 指定包含的静态资源类型 });

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!