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

如何在TypeScript中不导入库使用jQuery及其插件?

问题描述

我正在为jQuery Terminal项目开发一个基于Docusaurus和TypeScript的新网站,不想将库打包进项目,而是通过CDN加载最新版本。

当前已实现CDN加载依赖的代码(功能正常),但使用globalThis.jQuery时出现TypeScript错误:

Property 'jQuery' does not exist on type 'typeof globalThis'

尝试过两种方式但均无效:

  • 在src/types.ts中引入d.ts文件并配置到tsconfig,导入后无效果:
/// <reference path="../node_modules/@types/jquery/index.d.ts" />
/// <reference path="../node_modules/jquery.terminal/js/jquery.terminal.d.ts" />
  • 尝试扩展全局类型时,出现重复声明错误:

Cannot redeclare block-scoped variable 'jQuery'

declare global {
  var jQuery: JQueryStatic;
}

其他文件中已使用类型导入:

import type { JQueryTerminal, JQueryStatic } from 'jquery.terminal';
import type { Deferred } from 'jquery';

需求:在TypeScript中定义globalThis.jQuery的类型,同时不将库打包进项目。


解决方案

方法1:类型断言快速解决

在使用globalThis.jQuery的位置添加类型断言,临时规避类型检查:

// 精确断言版本
import type { JQueryStatic } from 'jquery';

const replReady = () => {
  const jQuery = globalThis.jQuery as unknown as JQueryStatic;
  return jQuery && jQuery.terminal;
};

或简化版:

const replReady = () => {
  return (globalThis as any).jQuery && (globalThis as any).jQuery.terminal;
};

方法2:正确扩展全局类型(无冲突)

由于@types/jquery已在全局声明jQuery,直接重新声明会冲突。可通过模块补充的方式扩展globalThis类型:

  1. 创建src/global-extensions.d.ts文件,内容如下:
import type { JQueryStatic } from 'jquery';

declare global {
  interface typeof globalThis {
    jQuery: JQueryStatic;
  }
}

// 标记为模块,避免全局变量冲突
export {};
  1. 在tsconfig.json的include数组中添加该文件,确保TypeScript能检测到:
{
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/global-extensions.d.ts"
  ]
}

方法3:改用window替代globalThis

浏览器环境中window与globalThis等价,且@types/jquery已默认在Window接口中声明了jQuery,可直接使用:

const replReady = () => {
  return window.jQuery && window.jQuery.terminal;
};

额外注意事项

  • 确保已安装类型依赖:
npm install --save-dev @types/jquery

(jquery.terminal自身携带类型文件,无需额外安装对应@types包)

  • Docusaurus静态渲染时,需确保不会执行依赖jQuery的代码,避免运行时错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 09:36:00