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

使用Rollup打包React组件npm包时遇组件解析错误求助

Rollup打包React组件npm包报错:Could not resolve component from "src/index.ts"

问题背景

我正在尝试将React组件封装为自定义npm包,目前遇到Rollup报错:Rollup: Could not resolve component from "src/index.ts"。该组件在常规React项目中可正常使用,但无法通过Rollup完成打包。

项目结构

(附项目结构截图)
(附package.json截图)

相关代码文件

src/index.ts

import LeetcodeCalendar from "./components/LeetcodeCalendar";

export default LeetcodeCalendar;

rollup.config.mjs

import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import terser from "@rollup/plugin-terser";
import typescript from "@rollup/plugin-typescript";
import { readFileSync } from 'fs';
import dts from "rollup-plugin-dts";
import peerDepsExternal from "rollup-plugin-peer-deps-external";

const packageJson = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));

export default [
  {
    input: "src/index.ts",
    output: [
      {
        file: packageJson.main,
        format: "cjs",
        sourcemap: true,
      },
      {
        file: packageJson.module,
        format: "esm",
        sourcemap: true,
      },
    ],
    plugins: [
      peerDepsExternal(),
      resolve({ extensions: [".js", ".ts", ".jsx", ".tsx"] }),
      commonjs(),
      typescript({
        noEmitOnError: true,
        tsconfig: './tsconfig.json',
        declaration: true,
        declarationDir: 'dist',
     }),
      terser(),
    ],
    external: ["react", "react-dom"],
  },
  {
    input: "src/index.ts",
    output: [{ file: packageJson.types, format: "es" }],
    plugins: [dts.default],
  },
];

tsconfig.json

{
  "compilerOptions": {
    "target": "ES5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "jsx": "react-jsx",
    "rootDir": "src"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

已尝试的解决方法

  • 将Rollup配置文件从rollup.config.js改为ESM模块格式的rollup.config.mjs
  • 尝试将components/LeetcodeCalendar的代码直接合并到index.tsx文件,但触发更多错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 06:00:04