Kotlin/JS编写jwt-decode库绑定时出现未定义报错如何解决
问题原因
两个报错分别来自两处绑定错误:
- jwtDecode is not a function:3.x及以上版本的jwt-decode采用ES模块默认导出规则,你当前的函数声明没有标记对应默认导出,Kotlin/JS会尝试读取模块对象下名为
jwtDecode的属性,实际函数存在于模块的default属性上,自然找不到对应函数。如果使用2.x旧版本,UMD模式下全局挂载的函数名为jwt_decode,和你声明的函数名不匹配也会触发该错误。 - InvalidTokenError is not defined:
InvalidTokenError是jwt-decode模块的命名导出项,不会挂载到JS全局作用域。你将其声明为无模块关联的顶层external类时,Kotlin/JS会直接到全局作用域查找该类的定义,自然无法找到。
正确绑定实现
以下是适配jwt-decode 3.x版本的正确Kotlin/JS绑定代码,Gradle侧的npm依赖声明不需要修改,原有业务调用逻辑也无需调整:
/** * jwt-decode 无效令牌错误类 */ @JsModule("jwt-decode") @JsNonModule @JsName("InvalidTokenError") external class InvalidTokenError : Throwable /** * jwt解码配置项 */ external interface JwtDecodeOptions { var header: Boolean? get() = definedExternally set(value) = definedExternally } /** * JWT头结构 */ external interface JwtHeader { var typ: String? get() = definedExternally set(value) = definedExternally var alg: String? get() = definedExternally set(value) = definedExternally var kid: String? get() = definedExternally set(value) = definedExternally } /** * JWT载荷结构 */ external interface JwtPayload { var iss: String? get() = definedExternally set(value) = definedExternally var sub: String? get() = definedExternally set(value) = definedExternally var aud: dynamic // 可能为字符串或字符串数组 get() = definedExternally set(value) = definedExternally var exp: Long? get() = definedExternally set(value) = definedExternally var nbf: Long? get() = definedExternally set(value) = definedExternally var iat: Long? get() = definedExternally set(value) = definedExternally var jti: String? get() = definedExternally set(value) = definedExternally } /** * JWT解码核心函数 */ @JsModule("jwt-decode") @JsNonModule @JsName("default") external fun <T> jwtDecode(token: String, options: JwtDecodeOptions = definedExternally): T
补充说明
- 上述写法同时支持浏览器UMD全局引入、CommonJS、ES模块三种模块加载场景,不需要额外调整。
- 如果使用2.x版本的jwt-decode,只需要去掉jwtDecode函数上的
@JsName("default")注解,同时给函数加上@JsName("jwt_decode")即可。 - 正确导入
InvalidTokenError后,原有try-catch逻辑可以正常匹配到对应错误类型,无需修改。
内容的提问来源于stack exchange,提问作者Jojo01
相关产品推荐
相关产品推荐

