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

如何构建并发布保持原目录结构的React组件库

解决Vite构建React组件库生成独立组件文件的问题

1. 调整Vite配置文件(vite.config.js)

通过配置build选项开启多入口,保留原组件目录结构:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
  plugins: [react()],
  build: {
    lib: {
      // 手动指定每个组件的入口文件
      entry: {
        Button: path.resolve(__dirname, 'src/components/Button/index.jsx'),
        Input: path.resolve(__dirname, 'src/components/Input/index.jsx'),
        Card: path.resolve(__dirname, 'src/components/Card/index.jsx'),
      },
      formats: ['es'], // 输出ES模块,适配现代项目
      fileName: (format, entryName) => `${entryName}/index.${format}.js`,
    },
    rollupOptions: {
      // 排除React依赖,让用户项目自行引入
      external: ['react', 'react-dom'],
      output: {
        preserveModules: true, // 禁止合并模块,生成独立文件
        preserveModulesRoot: 'src/components', // 对齐src目录结构
        assetFileNames: '[name].[ext]', // 保留静态资源原文件名
      },
    },
  },
});

2. 自动扫描组件入口(可选)

组件数量较多时,用Node.js的fs模块自动扫描组件目录,避免手动维护entry:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import fs from 'fs';

// 自动扫描src/components下的所有组件入口
function getComponentEntries() {
  const componentsDir = path.resolve(__dirname, 'src/components');
  const entries = {};

  fs.readdirSync(componentsDir).forEach(componentName => {
    const componentPath = path.join(componentsDir, componentName);
    if (fs.statSync(componentPath).isDirectory()) {
      const entryPath = path.join(componentPath, 'index.jsx');
      if (fs.existsSync(entryPath)) {
        entries[componentName] = entryPath;
      }
    }
  });

  return entries;
}

export default defineConfig({
  plugins: [react()],
  build: {
    lib: {
      entry: getComponentEntries(),
      formats: ['es'],
      fileName: (format, entryName) => `${entryName}/index.${format}.js`,
    },
    rollupOptions: {
      external: ['react', 'react-dom'],
      output: {
        preserveModules: true,
        preserveModulesRoot: 'src/components',
      },
    },
  },
});

3. 配置package.json

更新package.json字段,支持按需导入并声明发布文件:

{
  "name": "your-component-library",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": "./dist/index.es.js", // 根入口(若有统一导出文件)
    "./Button": "./dist/Button/index.es.js",
    "./Input": "./dist/Input/index.es.js",
    "./Card": "./dist/Card/index.es.js"
  },
  "files": [
    "dist"
  ]
}

如果存在统一导出所有组件的src/index.js,记得在build的entry中添加该文件,生成dist/index.es.js。

4. 验证构建结果

执行vite build命令后,dist目录会生成与src/components结构一致的组件目录,每个目录下对应独立的组件文件,符合你的预期结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:23:21