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

在Deno+Fresh项目中引入Headless-ui时遇TypeError问题求助

解决Deno Fresh中引入HeadlessUI出现的TypeError: Cannot read properties of undefined (reading '__H')错误

错误原因

该错误源于HeadlessUI React版本未正确适配Preact环境:HeadlessUI运行时会调用React的JSX相关内部逻辑,你的原导入配置未映射react/jsx-runtime到Preact的对应模块,导致Preact的虚拟DOM标识__H无法被正确识别。

解决方案

1. 修正HeadlessUI的导入链接

更新Island中的导入语句,补充react/jsx-runtime的别名映射,并使用兼容的HeadlessUI和Preact版本:

import { Switch } from "https://esm.sh/@headlessui/react@1.7.17?alias=react:preact/compat,react-dom:preact/compat,react/jsx-runtime:preact/jsx-runtime&deps=preact@10.17.1";
import { useState } from "preact/hooks";
import { tw } from "twind";

export default function () {
  const [checked, setChecked] = useState(false);
  const toggleChecked = () => setChecked(!checked);

  return (
    <Switch
      checked={checked}
      onChange={toggleChecked}
      class={tw`${
        checked ? "bg-blue-600" : "bg-gray-200"
      } relative inline-flex h-6 w-11 items-center rounded-full`}
    >
      <span class={tw`sr-only`}>Enable notifications</span>
      <span
        class={tw`${
          checked ? "translate-x-6" : "translate-x-1"
        } inline-block h-4 w-4 transform rounded-full bg-white`}
      />
    </Switch>
  );
}

2. 确认页面正确引用Island

确保在页面组件中正确导入并使用你的Island,比如在routes/index.tsx中:

import MySwitch from "../islands/MySwitch.tsx";

export default function Home() {
  return (
    <div class="p-8">
      <MySwitch />
    </div>
  );
}

3. 清除缓存并重启项目

执行以下命令清除旧依赖缓存,避免缓存导致的适配问题:

deno cache --reload
deno task start

额外检查

  • 确保使用最新稳定版Fresh,可在deno.json中更新依赖:
    {
      "imports": {
        "$fresh/": "https://deno.land/x/fresh@1.6.8/",
        // 其他依赖配置
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:10:34