我正在尝试生成 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
需要 jQuery
、document
和 window
在全局对象上定义,它们不在 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/