【避坑】Wails 无法生成前端绑定?解析 time.Time 导致的映射失败

【避坑】Wails 无法生成前端绑定?解析 time.Time 导致的映射失败

一、 问题描述

在进行 Wails 开发时,我们通常使用 wails devwails generate module 来自动将 Go 层的函数绑定(Binding)到前端的 wailsjs/go 目录下。

然而,最近在项目中发现,我在 app.go 中定义的函数突然无法在前端生成对应的映射,且没有任何明显的语法错误。

二、 排查与定位

尝试手动执行模块生成命令:

Bash

wails generate module

 

终端输出了如下报错信息:

Plaintext

2025/04/24 13:24:14 KnownStructs: model.TablePass  model.WailsCommunicate
Not found: time.Time

 

原因分析:

Wails 在生成 TypeScript 定义(TS Definitions)时,需要扫描 Go 结构体的字段类型。由于 time.Time 是 Go 标准库中的复杂结构,Wails 的代码生成器无法直接将其映射为前端原生的 Date 或 String 类型,从而导致整个结构体及其关联的函数绑定流程中断。


三、 解决方案:使用 ts_type 标签

解决办法非常简单:通过 Go 结构体的 Tag(标签),明确告诉 Wails 如何处理这个特殊类型。

我们可以使用 ts_type:"string" 标签,将 time.Time 在生成前端定义时强制声明为 string 类型。这样 Wails 在序列化 JSON 时会将其转为 RFC3339 格式的字符串,前端直接接收即可。

具体实现示例:

在结构体中,为所有 time.Time 类型的字段添加 ts_type:"string"

Go

type TablePass struct {
    ID        int       `gorm:"primary_key" json:"id"`
    Username  string    `gorm:"not null" json:"username"`
    Password  string    `gorm:"not null" json:"password"`
    Port      string    `gorm:"not null" json:"port"`
    Status    bool      `gorm:"not null" json:"status"`   
    Priority  int       `gorm:"not null" json:"priority"` 
    // 关键点:添加 ts_type:"string" 映射
    CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" ts_type:"string"`
    UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" ts_type:"string"`
}

 


四、 验证结果

修改完成后,再次执行绑定命令:

Bash

wails generate module

 

输出结果:

Plaintext

 
♥ If Wails is useful to you or your company, please consider sponsoring the project...

此时没有任何报错,前端 wailsjs/go 目录下也成功出现了对应的函数和模型定义,问题完美解决!


五、 总结与建议

  • 不仅仅是 time.Time:如果你在结构体中使用了其他第三方库的复杂类型,导致 Wails 报错 Not found,都可以尝试用 ts_type 进行手动映射。

  • 前端处理:由于后端映射成了 string,前端如果需要进行日期运算,记得使用 new Date(res.created_at)dayjs() 进行一次转换。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容