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

使用Vite打包发布类库时如何排除指定文件与文件夹?

解决Vite打包类库时仅包含lib文件夹的问题

你当前的配置问题出在几个关键点上:optimizeDeps.exclude和rollupOptions.external是用来排除第三方依赖的,不是过滤本地源码文件;另外Rollup的TypeScript插件没有限制处理范围,导致整个src下的类型声明都被输出到dist。

以下是修正后的vite.config.ts配置:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
import typescriptPaths from 'rollup-plugin-typescript-paths';
import typescript from '@rollup/plugin-typescript';

export default defineConfig({
  plugins: [
    react({
      jsxImportSource: "@emotion/react",
    }),
  ],
  optimizeDeps: {
    exclude: ["react"], // 仅排除第三方依赖,移除本地路径
  },
  build: {
    manifest: true,
    minify: true,
    reportCompressedSize: true,
    lib: {
      entry: resolve(__dirname, "src/lib/index.ts"),
      name: "my-awesome-lib",
      fileName: (format) => `my-awesome-lib.${format}.js`,
    },
    rollupOptions: {
      input: ["src/lib/index.ts"],
      external: ["react"], // 仅排除第三方依赖,移除本地路径
      output: {
        globals: {
          react: "React",
        },
      },
      plugins: [
        typescriptPaths({
          preserveExtensions: true,
        }),
        typescript({
          sourceMap: true,
          declaration: true,
          outDir: "dist",
          include: ["src/lib/**/*"], // 仅处理lib文件夹下的文件
          exclude: ["src/stories/**/*", "App.tsx", "main.tsx"], // 明确排除不需要的文件
        }),
      ],
    },
  },
});

额外需要调整tsconfig.json,确保TypeScript仅编译lib文件夹的内容:

{
  "compilerOptions": {
    // 你的原有配置...
    "outDir": "./dist"
  },
  "include": ["src/lib/**/*"],
  "exclude": ["src/stories", "App.tsx", "main.tsx", "node_modules"]
}

关键修改说明:

  • 移除了optimizeDeps.exclude和rollupOptions.external中的本地文件路径,这两个配置仅用于排除React这类第三方依赖,不能过滤本地源码。
  • 给Rollup的TypeScript插件添加include和exclude,限制它只处理src/lib下的文件,避免生成stories、App等文件的类型声明。
  • 同步调整tsconfig.json的include和exclude,确保TS编译范围正确,进一步防止多余文件被处理。

这样打包后,dist文件夹里只会包含从src/lib/index.ts出发的依赖文件和对应的类型声明,stories、App.tsx等无关文件不会被打包进去。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:52:44