在Bun中使用HTMX遇报错:Cannot find name 'htmx'.ts(2304)
解决Bun中导入HTMX后无法识别全局
htmx对象的问题 问题原因
直接执行import "htmx.org"时,HTMX的ES模块不会自动将htmx对象挂载到全局window,同时TypeScript无法识别未声明的全局变量,因此抛出Cannot find name 'htmx'.ts(2304)错误。
解决方案
方案1:显式导入并挂载到全局
将HTMX导入后手动挂载到window对象,同时直接使用导入的变量:
import htmx from "htmx.org"; import Sortable from "sortablejs"; // 挂载到全局(可选,若需在其他全局代码中使用htmx) (window as any).htmx = htmx; htmx.onLoad(function(content) { const sortables = content.querySelectorAll(".sortable"); sortables.forEach(sortable => { new Sortable(sortable, { animation: 150, ghostClass: 'blue-background-class' }); }); });
方案2:添加TypeScript类型声明
如果希望保持import "htmx.org"的导入方式,可通过类型声明让TS识别全局htmx:
- 在项目根目录创建
htmx.d.ts文件,内容如下:
declare var htmx: import("htmx.org").Htmx;
- 修改
tsconfig.json,确保类型声明文件被包含:
{ "compilerOptions": { // 其他配置 }, "include": ["./htmx.d.ts", "src/**/*"] }
- 之后即可直接导入并使用:
import "htmx.org"; import Sortable from "sortablejs"; htmx.onLoad(function(content) { const sortables = content.querySelectorAll(".sortable"); sortables.forEach(sortable => { new Sortable(sortable, { animation: 150, ghostClass: 'blue-background-class' }); }); });
方案3:使用CDN引入HTMX(可选)
跳过模块安装,直接在HTML中引入HTMX的CDN资源,全局htmx对象会自动注册:
<script src="https://unpkg.com/htmx.org@1.9.5"></script> <script src="https://unpkg.com/sortablejs@1.15.0/Sortable.min.js"></script>
若使用TypeScript,仍需添加方案2中的htmx.d.ts类型声明文件。
内容的提问来源于stack exchange,提问作者bear
相关产品推荐
相关产品推荐

