在使用 Vite 进行项目开发时,可以通过配置文件 vite.config.jsvite.config.ts 来自定义项目的构建和开发流程。以下是常见的 Vite 项目配置及其说明:

基本配置

// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': '/src',  // 路径别名
    },
  },
  server: {
    port: 3000,          // 本地开发服务器端口
    open: true,          // 自动打开浏览器
    proxy: {             // 代理设置
      '/api': {
        target: 'https://api.example.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
  build: {
    outDir: 'dist',      // 构建输出目录
    sourcemap: true,     // 生成 sourcemap 文件
    rollupOptions: {
      output: {
        // 静态资源打包分类
        assetFileNames: 'assets/[name].[hash].[ext]',
        chunkFileNames: 'js/[name].[hash].js',
        entryFileNames: 'js/[name].[hash].js',
      },
    },
  },
});

关键配置详解

  1. 插件系统(plugins):

    • 在 Vite 中,插件非常重要,@vitejs/plugin-vue 是 Vue 3 项目的核心插件。
  2. 路径别名(resolve.alias):

    • 通过设置 @src 的路径别名,简化模块导入时的路径引用。
  3. 开发服务器配置(server):

    • port: 自定义本地开发环境的端口,默认为 5173。
    • open: 启动开发服务器后自动在浏览器中打开项目。
    • proxy: 解决开发环境跨域问题,设置代理来将 /api 路径重写为目标服务器地址。
  4. 构建配置(build):

    • outDir: 自定义打包后的输出目录,默认为 dist
    • sourcemap: 启用源码映射,方便调试生产环境代码。
    • rollupOptions: 用于自定义 Rollup 的打包行为,例如自定义文件名、资源分类等。

其他常用配置

  1. CSS 预处理器支持:
    如果你使用了 Sass 或 Less,可以在 vite.config.js 中配置如下:

    export default defineConfig({
      css: {
        preprocessorOptions: {
          scss: {
            additionalData: `@import "@/styles/variables.scss";`
          }
        }
      }
    });
    
  2. 环境变量配置:
    Vite 支持根据不同的环境配置变量,例如 .env.env.production.env.development 文件。使用 import.meta.env 访问这些变量。

    # .env 文件
    VITE_API_URL=https://api.example.com
    
    // 在代码中使用
    const apiUrl = import.meta.env.VITE_API_URL;
    
  3. 模块联邦(Module Federation):
    如果项目需要使用模块联邦,可以通过 vite-plugin-federation 插件来配置。

优化建议

  1. 按需加载: 对于大项目,可以使用 dynamic import 来实现按需加载组件,减少首次加载时间。

    const MyComponent = () => import('@/components/MyComponent.vue');
    
  2. 代码分割(Code Splitting): 在 build.rollupOptions 中设置,确保大文件拆分为更小的块。

这就是一个使用 Vite 开发 Vue 项目的基础配置,你可以根据项目需求灵活调整配置文件。


在 Vite 项目中,开发配置和功能,适用于生产环境的优化、代码质量保障、提升开发体验等方面。

1. 动态导入和代码分割(Lazy Loading and Code Splitting)

在生产环境下,按需加载模块有助于减小打包体积和提升页面加载性能。

使用场景:组件按需加载
import { defineAsyncComponent } from 'vue';

// 定义异步组件
const AsyncComponent = defineAsyncComponent(() =>
  import('@/components/AsyncComponent.vue')
);

在路由层面,你可以结合 Vue Router 动态导入组件:

// router/index.js
const routes = [
  {
    path: '/home',
    component: () => import('@/views/Home.vue')  // 按需加载页面组件
  },
];

2. 自动导入(Auto-importing Plugins)

手动引入库或组件可能变得繁琐,尤其是大型项目。你可以使用 unplugin-auto-importunplugin-vue-components 来自动导入 Vue API 和组件。

安装依赖
npm install -D unplugin-auto-import unplugin-vue-components
配置 vite.config.js
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from 'unplugin-vue-components/resolvers';  // 如果使用Vant

export default defineConfig({
  plugins: [
    vue(),
    AutoImport({
      imports: ['vue', 'vue-router'],  // 自动导入Vue相关的API,比如ref、reactive等
      dts: 'src/auto-imports.d.ts',  // 自动生成类型声明文件
    }),
    Components({
      resolvers: [VantResolver()],  // 自动导入Vant组件
      dts: 'src/components.d.ts',
    }),
  ],
});

通过这两个插件,你可以避免在每个文件手动引入 refreactive 等,或者显式地导入第三方组件。

3. 环境变量和模式(Env Variables and Mode)

在大型项目中,你可能需要为不同的环境(开发、测试、生产)设置不同的环境变量。Vite 提供了 .env 文件支持。

创建不同的 .env 文件
# .env.development
VITE_API_URL=https://dev.api.example.com

# .env.production
VITE_API_URL=https://prod.api.example.com

在代码中,你可以通过 import.meta.env 访问这些环境变量:

const apiUrl = import.meta.env.VITE_API_URL;

4. 生产环境优化(Production Optimization)

配置 gzip 压缩

启用 gzip 压缩可以减少网络传输的数据大小,提升页面加载速度。

安装 vite-plugin-compression

npm install -D vite-plugin-compression

配置 vite.config.js

import compression from 'vite-plugin-compression';

export default defineConfig({
  plugins: [
    vue(),
    compression({
      algorithm: 'gzip',   // 使用gzip压缩
      ext: '.gz',          // 生成的压缩文件扩展名
    }),
  ],
});
配置 CSS 和 JS 压缩

通过优化构建的 CSS 和 JS 文件,减少生产环境的打包体积。Vite 默认使用 Terser 压缩 JS,你可以进行自定义。

export default defineConfig({
  build: {
    terserOptions: {
      compress: {
        drop_console: true,    // 移除console.log
        drop_debugger: true,   // 移除debugger
      },
    },
    cssCodeSplit: true,         // 启用CSS代码分割
  },
});
动态加载 Polyfills

对于旧浏览器的兼容性问题,你可以只在必要时加载 polyfill。使用 vite-plugin-legacy 实现。

安装依赖:

npm install -D @vitejs/plugin-legacy

配置:

import legacy from '@vitejs/plugin-legacy';

export default defineConfig({
  plugins: [
    vue(),
    legacy({
      targets: ['defaults', 'not IE 11'],  // 定义支持的浏览器
    }),
  ],
});

5. 按需国际化(On-demand i18n loading)

在多语言应用中,如果项目有大量的语言包文件,加载所有的语言文件会影响性能。可以按需加载所需的语言包。

const messages = {
  en: () => import('@/locales/en.json'),
  zh: () => import('@/locales/zh.json'),
};

const i18n = createI18n({
  locale: 'en',
  messages: {
    en: async () => await messages.en(),
    zh: async () => await messages.zh(),
  },
});

6. 基于 Monorepo 的多包管理(Monorepo Support)

如果你需要在同一个仓库中管理多个包,可以结合 Yarn workspaces 或 pnpm 的 monorepo 支持。

配置 pnpm-workspace.yaml
packages:
  - 'packages/*'
  - 'apps/*'

然后在 vite.config.js 中配置路径:

export default defineConfig({
  resolve: {
    alias: {
      '@core': '/packages/core/src',  // 例如 Monorepo 中的核心包
    },
  },
});

7. SSR(Server-Side Rendering)配置

如果你需要服务端渲染,Vite 提供了与 SSR 的良好集成。可以使用 vite-plugin-ssr 结合。

安装依赖:

npm install vite-plugin-ssr

配置 vite.config.js

import ssr from 'vite-plugin-ssr/plugin';

export default defineConfig({
  plugins: [vue(), ssr()],
  build: {
    ssr: true,  // 开启SSR构建
  },
});

8. 测试和代码质量保障(Testing and Linting)

ESlint 和 Prettier

确保代码风格一致性,使用 ESLint 和 Prettier。

安装依赖:

npm install -D eslint eslint-plugin-vue prettier eslint-config-prettier

配置 .eslintrc.js:

module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
    'prettier'
  ],
  rules: {
    'vue/multi-word-component-names': 'off',
  },
};
Vitest 测试

Vite 官方推荐使用 Vitest 来进行单元测试。

安装依赖:

npm install -D vitest

vite.config.js 中配置 Vitest:

import { defineConfig } from 'vite';

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
  },
});

运行测试:

npx vitest

这些高级配置涵盖了性能优化、开发效率提升和项目维护性保障等各个方面。在实际项目中,可以根据具体需求选择合适的配置来最大化项目的开发效率和生产性能。


Tree Shaking(树摇)技术

在 Vite 中,使用模块化和优化配置可以更好地利用 Tree Shaking(树摇)技术,从而删除未使用的代码或属性,减少最终的包体积。Vite 基于 ES Modules(ESM)和 Rollup,因此天然支持 Tree Shaking,但一些额外的配置和编写规范可以帮助优化 Tree Shaking 效果。

1. 使用 ES Modules 编写模块化代码

  • 确保使用 exportimport,而不是 module.exportsrequire(),因为 Tree Shaking 主要在 ESM 上生效。
  • 避免使用 export default,而倾向于命名导出(export const 等)。这样 Vite 更容易分析哪些导出是未使用的,从而进行删除。

示例:

// utils.js
export const helper1 = () => { /* ... */ };
export const helper2 = () => { /* ... */ };
export const unusedFunction = () => { /* ... */ }; // 未使用的函数

// main.js
import { helper1 } from './utils.js'; // 只导入使用到的函数
helper1();

在这种情况下,unusedFunction 没有被使用,因此 Tree Shaking 会在打包时将其删除。

2. 按需导入(Destructuring Imports)

  • 对于像 JSON 文件或大型模块,按需导入可以避免加载整个模块或文件的内容。通过解构导入所需的属性,Vite 可以更好地剔除未使用的部分。

示例:

// config.json
{
  "name": "Example",
  "version": "1.0.0",
  "description": "This is an example."
}

// 使用时按需导入
import { name } from './config.json'; // 仅导入 `name` 属性,其他属性会被 Tree Shaking 去除
console.log(name);

3. 配置 build.rollupOptions 以优化打包

vite.config.js 中,可以通过 build.rollupOptions 来配置 Rollup 的打包行为,以便更好地应用 Tree Shaking。

// vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
  build: {
    rollupOptions: {
      // 移除未使用的代码
      treeshake: true,
      output: {
        manualChunks: {
          // 配置分包,例如按需拆分 lodash 等库
          lodash: ['lodash']
        }
      }
    }
  }
});

这样可以确保在生产环境下,未使用的代码会被自动剔除。

4. 将大型库按需引入

如果你使用像 lodashmoment 等大型库,考虑使用按需引入方式,例如只引入特定方法,而不是整个库。这可以显著减少打包体积,并使 Tree Shaking 更有效。

示例:

// 推荐:按需导入 lodash 方法
import debounce from 'lodash/debounce';

debounce(() => { /* ... */ });

// 不推荐:整个 lodash 库被导入,Tree Shaking 无法去除未使用的部分
import _ from 'lodash';

或者使用 lodash-es,它是原生支持 ESM 的版本,比 lodash 更适合 Tree Shaking。

5. 避免动态导入(Dynamic Imports)中的全部导入

动态导入可以按需加载模块,但避免使用 import * as 的形式,因为这会引入整个模块。尽量明确导入所需的具体函数或属性。

示例:

// 推荐:只动态导入特定的导出
import('./module').then(({ specificFunction }) => {
  specificFunction();
});

// 不推荐:动态导入整个模块,影响 Tree Shaking
import('./module').then((module) => {
  module.specificFunction();
});

6. 在生产模式下启用 Tree Shaking

Vite 会在生产模式(vite build)下自动启用 Tree Shaking,但在开发模式下(vite dev),为优化构建速度,可能会禁用 Tree Shaking。所以在开发时,未使用的代码可能依然存在,但在生产环境中会被去除。

  • 使用 ESM 的 importexport,避免 default 导出。
  • 按需导入属性和函数,尤其是大型 JSON 文件和工具库。
  • 配置 Vite 的 build.rollupOptions,优化打包。
  • 对于大型库,使用 lodash-es 或按需加载库的特定模块。
  • 避免动态导入中的整体导入。

这样配置后,Vite 会更高效地应用 Tree Shaking,从而去除未使用的代码和属性,优化应用的体积和性能。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐