在Node.js的TypeScript 1.6.2中导入jQuery
我正在使用Node.js工作在一个爬虫。 我使用jQueryparsing使用jsdom
构build的页面。
我通过tsd
发现了一个jquery.d.ts ,它的结尾是这样的:
declare module "jquery" { export = $; } declare var jQuery: JQueryStatic; declare var $: JQueryStatic;
这个定义似乎只适用于jQuery在全局加载或全局窗口variables可用的客户端…
正如这里所解释的,当在window.document
不可用的环境(如Node.js)中导入(使用require
)时,jQuery会导出一个必须使用窗口对象初始化的工厂:
// 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
函数,我没有成功实现这个function。
作为一个小例子,现在基本上可以这样使用:
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 }