在 Node.js 的 TypeScript 1.6.2 中导入 jQuery

Import jQuery in TypeScript 1.6.2 in Node.js

我正在使用 Node.js 开发爬虫。我使用 jQuery 来解析使用 jsdom.

我通过tsd找到了一个jquery.d.ts,结尾是这样的:

declare module "jquery" {
    export = $;
}
declare var jQuery: JQueryStatic;
declare var $: JQueryStatic;

这个定义似乎只能在加载了 jQuery 的客户端上使用 全局或全局 window 变量可用的地方...

here所述, 在 window.document 不存在的环境中导入(使用 require)时 available (like Node.js), jQuery export a factory of itself 必须是 用 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'

但是现在我有这个奇怪的错误?!

我回答我的问题:

我已经很接近了,现在,我的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);
        });
    });
}

通过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
}