YUICompressor压缩JS报missing : after property id错误解决方法
报错原因
当前使用的JS压缩工具内置的语法解析器版本过低,不支持ES6标准的对象解构赋值语法,会将const { toggle } = window.cdn.createAnimation('Ff8rx6E4')这句解构代码错误识别为对象字面量定义,判定大括号内的属性缺少键值对分隔冒号,最终抛出missing : after property id错误。
修复方案
放弃对象解构写法,改为先存储createAnimation方法返回的实例,再通过点运算符取实例上的toggle方法即可。该写法和原解构逻辑完全等价,不会改变原有运行逻辑,同时能兼容所有版本的JS压缩校验工具:
const animationIns = window.cdn.createAnimation('Ff8rx6E4'); const toggle = animationIns.toggle; document.querySelector('#btn-mobile-openapp').onclick = toggle;
避坑提示:不要为了简写直接写成链式调用
document.querySelector('#btn-mobile-openapp').onclick = window.cdn.createAnimation('Ff8rx6E4').toggle,如果toggle方法内部依赖实例上下文,这种写法会导致this指向丢失,功能异常。如果运行时出现上下文错误,可手动绑定实例上下文:const animationIns = window.cdn.createAnimation('Ff8rx6E4'); const toggle = animationIns.toggle.bind(animationIns); document.querySelector('#btn-mobile-openapp').onclick = toggle;
内容的提问来源于stack exchange,提问作者CodeTrek
相关产品推荐
相关产品推荐

