![](/img/trans.png)
[英]Register a function to window (global scope) from a require.js module?
[英]adding document in global scope in typescript, accessible by node_module using require.js
我仍在学习关于Typescript的方法,并且有一个在node.js中运行的脚本,其中包括一个node_module,需要访问document
和XMLHttpRequest
。
我的想法是,如果我使用具有打字稿定义的jsdom
,我将能够创建一个包含document
和XMLHttpRequest
的全局对象。
但是,在索引文件中,我创建了
/// <reference path="./index.d.ts" />
const jsdom = require('jsdom');
document = jsdom('');
window = document.defaultView;
其中index.d.tx
是
declare var document: Document;
declare var window: Window;
当我运行测试时,包含的node_module返回错误ReferenceError: document is not defined
我已经看过并尝试了所有定义全局的方法,例如
export interface Global {
document: Document;
window: Window;
}
declare var global: Global;
和
declare module NodeJS {
interface Global {
document: Document,
window: Window
}
}
后者允许我在index.ts中定义
<reference path="./index.d.ts" />
const jsdom = require('jsdom');
document = jsdom('');
window = document.defaultView;
global.document = document;
global.window = window;
不幸的是,无论我做什么, document
都不会在全局名称空间中定义,并且展望未来,我还需要能够全局定义XMLHttpRequest
。
问题不在于您没有在TypeScript中正确定义类型-而是Node处于严格模式下并防止您意外创建全局变量。
您几乎可以肯定使用--use-strict
运行节点的版本-您可以:
要么
global.document = jsdom('');
直接分配给global
等 如果您确实需要全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.