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

如何用Vite创建无需入口文件与桶文件的大型TypeScript类库?

用Vite创建无需维护桶文件的多入口TypeScript类库

针对你的场景——拆分包含数百个独立React组件的类库,且不想手动维护大量桶文件(如index.ts),可以通过以下步骤用Vite实现:

1. 自动配置多入口构建

不用手动逐个指定入口文件,用Node的glob模块自动扫描所有组件文件,动态生成Vite的构建入口。

假设你的React组件都放在src/components/目录下,每个组件对应单独的.tsx文件,在vite.config.ts中配置如下:

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

// 自动扫描所有组件文件生成入口映射
const generateEntries = () => {
  const componentFiles = glob.sync('src/components/**/*.tsx');
  const entries: Record<string, string> = {};

  componentFiles.forEach(filePath => {
    const componentName = path.basename(filePath, '.tsx');
    entries[componentName] = path.resolve(__dirname, filePath);
  });

  return entries;
};

export default defineConfig({
  plugins: [react()],
  build: {
    lib: {
      entry: generateEntries(), // 动态生成的多入口
      formats: ['es', 'cjs'], // 同时输出ES模块和CommonJS格式
      fileName: (format, entryName) => `${entryName}.${format === 'es' ? 'mjs' : 'cjs'}`,
    },
    rollupOptions: {
      // 排除React等外部依赖,让使用方自行安装
      external: ['react', 'react-dom'],
      output: {
        globals: {
          react: 'React',
          'react-dom': 'ReactDOM',
        },
      },
    },
    outDir: 'dist',
    sourcemap: true,
  },
});

这样Vite会为每个组件单独打包,输出如dist/Button.mjs、dist/Input.cjs这类文件,完全不需要手动维护入口列表。

2. 自动生成类型声明

确保类库提供完整的TypeScript类型支持,在tsconfig.json中开启类型声明生成:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "jsx": "react-jsx",
    "declaration": true,
    "declarationDir": "dist/types",
    "emitDeclarationOnly": true,
    "strict": true,
    "moduleResolution": "bundler",
    "isolatedModules": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

然后在package.json中添加类型生成脚本:

{
  "scripts": {
    "build": "vite build && tsc",
    "build:types": "tsc --emitDeclarationOnly"
  }
}

3. 配置package.exports支持直接导入

为了让其他团队可以直接通过import Button from '@your-ui-lib/Button'的方式导入组件,需要动态生成package.json的exports字段,避免手动维护映射关系。

编写一个Node脚本scripts/generate-exports.js:

const fs = require('fs');
const path = require('path');
const { glob } = require('glob');

const packagePath = path.resolve(__dirname, '../package.json');
const pkg = require(packagePath);

const componentFiles = glob.sync('src/components/**/*.tsx');
const exportsMap = {
  ".": {
    "import": "./dist/index.mjs",
    "require": "./dist/index.cjs",
    "types": "./dist/types/index.d.ts"
  }
};

componentFiles.forEach(filePath => {
  const componentName = path.basename(filePath, '.tsx');
  const typePath = filePath.replace('.tsx', '.d.ts').replace('src/', 'dist/types/');
  
  exportsMap[`./${componentName}`] = {
    "import": `./dist/${componentName}.mjs`,
    "require": `./dist/${componentName}.cjs`,
    "types": `./${typePath}`
  };
});

pkg.exports = exportsMap;
fs.writeFileSync(packagePath, JSON.stringify(pkg, null, 2));

然后在package.json的scripts中添加前置脚本,构建前自动生成exports:

{
  "scripts": {
    "prebuild": "node scripts/generate-exports.js",
    "build": "vite build && tsc"
  }
}

4. 可选:自动生成根入口文件

如果需要支持从根路径批量导入(如import { Button, Input } from '@your-ui-lib'),可以编写脚本自动生成src/index.ts,无需手动维护:

创建scripts/generate-index.js:

const fs = require('fs');
const path = require('path');
const { glob } = require('glob');

const componentFiles = glob.sync('src/components/**/*.tsx');
let indexContent = '';

componentFiles.forEach(filePath => {
  const componentName = path.basename(filePath, '.tsx');
  indexContent += `export { default as ${componentName} } from './components/${componentName}';\n`;
});

fs.writeFileSync(path.resolve(__dirname, '../src/index.ts'), indexContent);

更新prebuild脚本,先生成根入口再处理exports:

{
  "scripts": {
    "prebuild": "node scripts/generate-index.js && node scripts/generate-exports.js",
    "build": "vite build && tsc"
  }
}

这样Vite会同时打包根入口文件,满足不同的导入习惯,且全程无需手动维护桶文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:23:17