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

Next.js+TypeScript环境下Cannot find name 'Annotorious'报错如何解决?

报错原因

通过<script>标签全局引入的Annotorious会挂载在window对象上,TypeScript默认没有对该全局变量的类型定义,因此会抛出Cannot find name 'Annotorious'的错误。

解决方案

方案1:新增全局类型声明(最常用,可保留类型提示)

  1. 在项目根目录下新建global.d.ts类型声明文件,写入以下内容:
declare global {
  interface Window {
    Annotorious: {
      init: (config: {
        image: string | HTMLElement;
        readOnly?: boolean;
        // 可根据实际使用的API补全其余配置字段
      }) => {
        loadAnnotations: (path: string) => void;
        on: (eventName: string, callback: (data: any) => void) => void;
        // 可根据实际使用的API补全其余实例方法
      }
    }
  }
}
// 必须导出才能让TS识别为全局类型文件
export {};
  1. 调用时从window对象上取值,避免全局作用域查找报错:
useEffect(()=>{
  setTimeout(() => {
    // 改为从window上取Annotorious
    var anno = window.Annotorious.init({
      image: "raven_cafe",
      readOnly: true,
    });
    anno.loadAnnotations('/scripts/annotations.w3c.json');
    anno.on('selectAnnotation', function(data) {
      let element = document.querySelector(`g[data-id="`+data.id+`"]`);
      element.classList.remove('selected');
    });
  }, 100);
},[]);

方案2:临时忽略类型检查(仅适合临时调试)

在调用Annotorious的代码前添加@ts-ignore注释,强制跳过该行的类型检查:

// @ts-ignore
var anno = Annotorious.init({
  // 原有配置
})

该方案会丢失类型提示,不建议长期使用。

方案3:改用npm包引入(适合长期维护项目)

直接安装Annotorious的官方npm包,比全局引入更易管控版本:

npm install @recogito/annotorious

安装完成后在组件顶部直接引入即可:

import * as Annotorious from '@recogito/annotorious'

额外优化建议

你当前给脚本加了async属性,脚本加载完成的时间不固定,100ms的定时器有可能出现脚本还没加载完成就执行初始化逻辑的问题,建议把脚本的async属性改为defer,或者监听脚本加载完成事件后再执行初始化逻辑,避免运行时报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:36:04