You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code扩展如何修复悬停时错误匹配rbxassetid资源ID的问题

问题根因

你遇到的误匹配问题是两个代码缺陷共同导致的:

  • 没有判断getWordRangeAtPosition的返回值:当光标悬停位置没有符合正则的内容时,该方法返回undefined,调用document.getText(undefined)会返回整个文档的完整内容,此时执行正则匹配会捕获到文档中第一个符合条件的ID,也就是你看到的一直返回1818的原因。
  • 没有提前终止逻辑:即使没有匹配到有效ID,代码依然会继续执行接口请求、生成悬停内容返回,VS Code就会将错误内容展示出来。
修改方案

调整正则逻辑,增加多层非空判断,没有匹配到有效资源ID时直接返回空,不生成悬停内容,修改后代码如下:

let disposable = vscode.languages.registerHoverProvider(['lua', 'luau'], {
    async provideHover(document, position, token) {
        // 正则添加^$锚点,确保只有完整匹配rbxassetid格式的单词才会被识别
        const range = document.getWordRangeAtPosition(position, /^rbxassetid:\/\/\d+$/);
        // 未匹配到有效范围直接返回,不生成悬停
        if (!range) return undefined;

        const word = document.getText(range);
        const idMatch = /rbxassetid:\/\/(\d+)/.exec(word);
        // 未匹配到有效ID直接返回
        if (!idMatch?.[1]) return undefined;

        const id = idMatch[1];
        console.log(`Found ${id}, fetching thumbnail info...`);
        const response = await fetch(`<roblox-thumbnail-api>`);
        const data = await response.json() as RobloxThumbnailResponse;
        const image = data.data?.[0]?.imageUrl;
        // 未获取到有效缩略图链接也不生成悬停
        if (!image) return undefined;

        console.log(image);
        const mdString = new vscode.MarkdownString(`Asset: ${id}\n<img src="${image}" height="150px">`);
        mdString.supportHtml = true;
        return new vscode.Hover(mdString);
    }
});
核心修改说明
  • 给getWordRangeAtPosition的正则添加了^和$锚点,避免部分匹配内容被误识别为资源ID
  • 增加了三层非空校验,只要任意环节没有拿到有效内容就直接返回undefined,VS Code会忽略无返回的悬停请求,不会展示错误内容

内容的提问来源于stack exchange,提问作者Saige Leah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 05:24:03