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

如何让Vite构建的React组件库支持shared-ui/组件名式导入

实现组件级路径导入的解决方案

要实现import { Select } from "shared-ui/select"这类子路径导入,需要调整Vite打包配置和package.json的导出规则,具体步骤如下:

1. 修改Vite配置,支持多入口打包

原来的配置只打包了单个总入口,现在需要为每个组件单独配置入口,让Vite生成独立的组件模块文件。更新vite.config.js的build.lib部分:

// vite.config.js
import { defineConfig, resolve } from 'vite';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import path from 'path';

export default defineConfig({
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
  build: {
    lib: {
      // 多入口配置:键为子路径名称,值为组件入口文件路径
      entry: {
        index: resolve(__dirname, "src/index.js"), // 保留总入口,兼容原有导入方式
        select: resolve(__dirname, "src/components/select/index.js"),
        input: resolve(__dirname, "src/components/input/index.js"),
        // 新增组件时在这里添加对应入口
      },
      formats: ["es"],
      // 使用[name]占位符,根据入口键生成对应文件名
      fileName: (format, entryName) => `${entryName}.js`,
    },
    rollupOptions: {
      plugins: [peerDepsExternal()],
      output: {
        globals: {
          react: "React",
        },
      },
    },
  },
});

执行vite build后,dist目录会生成index.js、select.js、input.js等独立文件。

2. 配置package.json的exports字段

exports字段是Node.js和包管理器识别子路径导入的核心配置,在组件库的package.json中添加以下内容:

{
  "name": "shared-ui",
  "type": "module", // 声明为ES模块
  "exports": {
    ".": "./dist/index.js", // 对应import ... from "shared-ui"
    "./select": "./dist/select.js", // 对应import ... from "shared-ui/select"
    "./input": "./dist/input.js", // 对应import ... from "shared-ui/input"
    "./package.json": "./package.json" // 必须配置,避免包管理器解析错误
  },
  // 兼容旧的导入方式,可选但建议保留
  "main": "./dist/index.js",
  "module": "./dist/index.js"
}

3. 确保组件入口文件正确导出

每个组件的index.js需要正确导出组件,比如src/components/select/index.js:

// src/components/select/index.js
export { default as Select } from './select.component.jsx';

同理,input组件的入口文件也要对应导出Input组件。

验证导入

完成上述配置后,重新执行vite build,在pnpm workspace的项目中即可使用以下方式导入组件:

// 原有导入方式依然可用
import { Select, Input } from 'shared-ui';

// 新的组件级路径导入
import { Select } from 'shared-ui/select';
import { Input } from 'shared-ui/input';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:10:31