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

在craco项目中使用含HeadlessUI Dialog的组件库组件报错求助

问题分析与解决方案

以下是针对你在Craco项目中使用自定义TestDialog组件出现的错误,给出的排查和解决步骤:

1. 检查导入/导出匹配性

你的TestDialog是命名导出,确认Craco项目中使用正确的导入方式:

  • 错误示例:
    import TestDialog from '@test/ui-components'
    
  • 正确示例:
    import { TestDialog } from '@test/ui-components'
    

2. 调整组件库依赖配置

将@headlessui/react移至package.json的peerDependencies,避免组件库打包时重复引入该依赖,导致模块冲突:

{
  "peerDependencies": {
    "@headlessui/react": "^1.7.0",
    "react": "^17.0.0 || ^18.0.0",
    "react-dom": "^17.0.0 || ^18.0.0"
  }
}

3. 配置Craco优先解析ES模块

在craco.config.js中添加webpack解析规则,让项目优先加载组件库的ES模块版本:

module.exports = {
  webpack: {
    resolve: {
      extensions: ['.ts', '.tsx', '.js', '.jsx'],
      mainFields: ['module', 'main'],
    },
  },
}

4. 修正Headless UI Dialog的使用方式

Headless UI的Dialog组件需要配合官方指定的子组件(如Dialog.Overlay、Dialog.Panel)使用,原代码的结构不符合要求,修正后的组件代码:

import { Dialog } from '@headlessui/react';
import React, { useState } from 'react';

export const TestDialog: React.FC = () => {
  let [isOpen, setIsOpen] = useState(true);

  return (
    <Dialog open={isOpen} onClose={() => setIsOpen(false)} className="relative z-10">
      {/* 遮罩层 */}
      <Dialog.Overlay className="fixed inset-0 bg-black/25" />
      {/* 弹窗容器 */}
      <div className="fixed inset-0 flex items-center justify-center p-4">
        <Dialog.Panel className="bg-white p-6 rounded-lg shadow-lg">
          <p>
            Are you sure you want to deactivate your account? All of your data will
            be permanently removed. This action cannot be undone.
          </p>
          <div className="mt-4 flex gap-3">
            <button onClick={() => setIsOpen(false)}>Deactivate</button>
            <button onClick={() => setIsOpen(false)}>Cancel</button>
          </div>
        </Dialog.Panel>
      </div>
    </Dialog>
  );
};

5. 检查组件库TypeScript编译配置

确保组件库的tsconfig.json配置符合React组件库的编译要求:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "jsx": "react-jsx",
    "declaration": true,
    "declarationDir": "./dist",
    "outDir": "./dist",
    "strict": true,
    "moduleResolution": "NodeNext",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}

内容的提问来源于stack exchange,提问作者David Díaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:45:42