jquery - dts-gen引用错误: jQuery is not defined

标签 jquery typescript

我正在尝试生成 jquery-colorbox 的定义文件。我从我的项目根目录使用:

dts-gen -m jquery-colorbox

失败并显示:

Unexpected crash! Please log a bug with the commandline you specified.
/usr/local/lib/node_modules/dts-gen/bin/lib/run.js:130
        throw e;
        ^

ReferenceError: jQuery is not defined
    at Object.<anonymous> (/home/adr/Projects/albums/node_modules/jquery-colorbox/jquery.colorbox.js:1105:3)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/dts-gen/bin/lib/run.js:57:67)
    at Module._compile (module.js:653:30)

我确实安装了 jQuery 和其他必需的库(全局和本地)。我如何“告诉”dts-gen“加载”/“使用”jQuery?

最佳答案

第一个问题是 dts-gen 需要实际加载您指定的模块才能检查其结构,而 jquery-colorbox 需要 jQuerydocumentwindow 在全局对象上定义,它们不在 Node.js 中。一种可能的方法(我没有采用)是使用 dts-gen 对 browser-based generation of declarations 的实验性支持。 。另一种方法是加载与 Node.js 兼容的 DOM 实现(例如 jsdom)并设置必要的全局变量,以便可以成功加载 jquery-colorbox。具体来说,如果您在名为 jquery-colorbox-wrapper.js 的文件中编写以下内容(基于 this answer ):

var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.jQuery = require('jquery')(window);
global.document = document;
global.window = window;
require("jquery-colorbox");

然后运行dts-gen --expression-file jquery-colorbox-wrapper.js,它应该会成功运行。

然后你会遇到第二个问题:生成的声明文件是空的,因为 jquery-colorbox 作为 jQuery 插件,向 jQuery 对象添加内容并且没有自己的导出。如果您更改包装器脚本以返回 jQuery 对象,那么您将获得 jquery-colorbox 的声明与 jQuery 本身的声明混合在一起。一个合理的方法是区分您获得的带有和不带有 jquery-colorbox 的 jQuery 声明文件。即,将 global.jQuery; 附加到上面给出的 jquery-colorbox-wrapper.js 文件,运行 dts-gen 一次,然后注释输出 require("jquery-colorbox"); 行并使用不同的输出文件再次运行 dts-gen,最后比较两个文件。这给我留下了 jquery-colorbox 特定的声明以及 sizzle* 变量中的一些差异,这些变量的名称包含时间戳,应该很容易删除。当然,声明文件需要大量清理。

关于jquery - dts-gen引用错误: jQuery is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53055091/

相关文章:

angular - typescript - 使用 "@"符号导入自定义类

angular - 如何从 component.ts 暂停或停止 HTML5 Audio 元素

javascript - 使用 css 和 jQuery 制作字母动画

javascript - 自动图像裁剪 JavaScript 工具建议

javascript - 如何检测 jQuery 全局变量何时准备好?

javascript - 如何将 fancybox 绑定(bind)到动态添加的元素?

jquery - 在附加列表项上添加 jQuery UI 按钮?

javascript - 在一个函数中同时处理 React.KeyboardEvent 或 React.MouseEvent

javascript - 合并 2 个数组对象 typescript

reactjs - 当从 safari 使用 qr-code-styling 下载 QRcode 时,图像中心缺少 Logo