我正在用Node.js开发一个爬虫。我使用jQuery来解析使用jsdom
构建的页面。
我通过tsd
找到了一个tsd
,其结尾如下:
declare module "jquery" {
export = $;
}
declare var jQuery: JQueryStatic;
declare var $: JQueryStatic;
这个定义似乎只适用于客户端,当jQuery全局加载或全局窗口变量可用时.
正如解释过的这里一样,在无法使用window.document
(如Node.js)的环境中导入(使用window.document
)时,jQuery导出其自身的工厂,该工厂必须使用window对象进行独立化:
// JavaScript (ES5)
var jquery = require("jquery");
// ...
var $ = jquery(window);
但是对于TypeScript,因为定义不包含这个工厂。这不管用:
// TypeScript
import jquery from "jquery"; // Module '"jquery"' has no default export
import {jquery} from "jquery" // Module '"jquery"' has no exported member 'jquery'
import {jQuery} from "jquery" // Module '"jquery"' has no exported member 'jQuery'
import {$} from "jquery" // Module '"jquery"' has no exported member '$'
import * as jquery from "jquery"; // Doesn't complain here, but `jquery` variable is not usable
我试着为这个工厂写一个定义,但它似乎没有我想的那么简单:
interface JQueryFactory {
(window: any): JQueryStatic;
}
declare module "jquery" {
export default JQueryFactory;
}
declare var jQuery: JQueryStatic;
declare var $: JQueryStatic;
并使用它:
// TypeScript
/// <reference path="../../typings/tsd.d.ts"/>
import jquery from "jquery";
// ...
var $ = jquery(window); // error TS2304: Cannot find name 'jquery'
但现在我有了这个奇怪的错误?!
发布于 2015-11-13 10:20:43
我回答我的问题:
我当时非常接近,现在,我的jquery.d.ts
就这样结束了:
declare var jQuery: JQueryStatic;
declare var $: JQueryStatic;
declare function jQueryFactory (window: any): JQueryStatic;
declare module "jquery" {
export default jQueryFactory;
}
在不声明jQueryFactory
函数的情况下,我无法成功地做到这一点。
作为一个小例子,它现在基本上可以这样使用:
import {env} from "jsdom";
import jquery from "jquery";
interface StuffInterface
{
title: string;
text: string;
}
function parse (url: string): Promise<StuffInterface>
{
return new Promise((resolve, reject) => {
env(url, (e, window) => {
if (e) {
reject(e);
return;
}
var $ = jquery(window);
var stuff = {
title: $('#stuff h1').text(),
text: $('#stuff .content').text()
};
resolve(stuff);
});
});
}
发布于 2016-03-21 09:51:26
不污染TypeScript 1.8.9
的jquery.d.ts
main.ts
require.config({
baseUrl: '/js',
shim: {
jquery: {
exports: '$' // Trick here!!!
},
underscore: {
exports: '_' // Trick here!!!
}
},
paths: {
jquery: 'lib/jquery.min',
underscore: 'lib/underscore.min'
}
});
require(['foobar'], function (foobar) {
foobar.runMe();
});
foobar.ts
import 'jquery';
import 'underscore';
export function runMe() {
console.log($); // this print jquery object
console.log(_); // this print underscore object
}
https://stackoverflow.com/questions/33699062
复制相似问题