You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Vite在Library Mode下仅构建指定Vue组件?

单个仓库下单独打包Vue组件(Vite库模式)

需求背景

在单个仓库中开发多个可插拔Vue组件,每个组件独立存放在src的子目录中,无需一次性打包全部组件,避免Monorepo或Multirepo的管理复杂度,最终输出.mjs格式文件,导出名为Renderer。

目录结构如下:

.
└── src
    ├── textWithBlueBackground
    |   ├── index.ts(导入TextWithBlueBackground并导出为Renderer)
    |   └── TextWithBlueBackground.vue
    └── textWithRedBackground
        ├── index.ts(导入TextWithRedBackground并导出为Renderer)
        └── TextWithRedBackground.vue

解决方案

方法1:通过环境变量动态指定入口

修改vite.config.ts,让构建入口读取环境变量,实现动态指定组件:

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

export default defineConfig(() => {
  // 从环境变量获取要打包的组件目录名
  const componentName = process.env.COMPONENT_NAME

  return {
    plugins: [vue()],
    build: {
      lib: {
        // 动态拼接组件入口路径
        entry: resolve(__dirname, `./src/${componentName}/index.ts`),
        name: 'Renderer',
        fileName: 'renderer',
      },
      rollupOptions: {
        external: ['vue'],
        output: {
          globals: {
            vue: 'Vue',
          },
        },
      },
    },
  }
})

执行构建命令

  • macOS/Linux:
COMPONENT_NAME=textWithBlueBackground vite build
  • Windows(CMD):
set COMPONENT_NAME=textWithBlueBackground && vite build

也可以在package.json中配置脚本,简化操作:

{
  "scripts": {
    "build:blue": "COMPONENT_NAME=textWithBlueBackground vite build",
    "build:red": "COMPONENT_NAME=textWithRedBackground vite build"
  }
}

执行npm run build:blue即可打包蓝色背景文本组件。

方法2:直接通过CLI参数指定入口

无需修改vite.config.ts(可保留原配置,或留空entry),直接通过--build.entry参数指定单个组件的入口文件:

vite build --build.entry ./src/textWithBlueBackground/index.ts

这种方式更灵活,无需提前配置脚本,直接在命令行指定要打包的组件路径即可。

效果说明

两种方法最终都会生成仅包含目标组件的.mjs文件,导出内容为该组件的Renderer,完全满足单个组件独立打包的需求,无需引入Monorepo或Multirepo的管理成本。

内容的提问来源于stack exchange,提问作者baitendbidz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 10:25:21