繁体   English   中英

使用typescript在全局范围内添加文档,node_module可使用require.js访问

[英]adding document in global scope in typescript, accessible by node_module using require.js

我仍在学习关于Typescript的方法,并且有一个在node.js中运行的脚本,其中包括一个node_module,需要访问documentXMLHttpRequest

我的想法是,如果我使用具有打字稿定义的jsdom ,我将能够创建一个包含documentXMLHttpRequest的全局对象。

但是,在索引文件中,我创建了

/// <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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM