Alpine.js与Astro开发中VS Code报Identifier expected.ts(1003)错误求助
解决Alpine.js + Astro中
x-on:click.outside的TypeScript错误 问题场景
我在用Alpine.js(3.11.1)搭配Astro.build(2.0.13)开发,给div元素加了这段代码:
<div x-on:click.outside="shownav = false"></div>
但VS Code(1.74.3)里的.位置一直报TypeScript错误:Identifier expected.ts(1003),我用的是TypeScript 4.9.5,折腾了好久没搞定,求解决方法。
针对Identifier expected.ts(1003)的解决步骤
这个错误是因为TypeScript默认不识别Alpine.js的事件修饰符语法,需要扩展Astro的JSX类型声明:
- 在项目
src目录下新建(或编辑已有的)custom-attributes.d.ts文件 - 把下面的代码加进去:
declare namespace astroHTML.JSX { interface HTMLAttributes { 'x-on:click.outside'?: string; // 要是还有其他带修饰符的Alpine事件,比如click.away、keyup.enter,也可以在这里依次添加 } }
附带相关错误的解决方案
如果有人碰到Property 'outside' does not exist on type 'HTMLAttributes'.ts(2322)的错误,同样在src/custom-attributes.d.ts里加这段代码就能解决:
declare namespace astroHTML.JSX { interface HTMLAttributes { outside?: string; } }
小提示
保存文件后要是错误还在,试试按Ctrl+Shift+P打开命令面板,选TypeScript: Restart TS Server重启一下语言服务,一般就能生效了。
内容的提问来源于stack exchange,提问作者gelviis
相关产品推荐
相关产品推荐

