dts-gen ReferenceError:未定义jQuery

时间:2018-10-29 22:56:09

标签: 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?

1 个答案:

答案 0 :(得分:2)

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

jquery-colorbox-wrapper.js

然后运行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插件,将内容添加到jQuery对象中,并且没有自己的导出。如果更改包装器脚本以返回jQuery对象,则将获得jquery-colorbox的声明和jQuery本身的声明的混合。合理的方法是区分使用和不使用jquery-colorbox的jQuery声明文件。即,将jquery-colorbox附加到如上所述的global.jQuery;文件中,运行jquery-colorbox-wrapper.js一次,然后注释掉dts-gen行,并以不同的输出再次运行require("jquery-colorbox");文件,最后比较两个文件。这给我留下了dts-gen特定的声明以及jquery-colorbox变量中的一些差异,这些变量的名称包含时间戳,应该易于删除。当然,声明文件将需要大量清理。