使用.d.ts。用于 Node 和 Web-Worker 的 JS 文件

Using .d.ts. files for JS intended for Node and a Web-Worker

我在脚本中使用库 Q,我想在网络工作者和 Node 中 运行。如果我这样引用 q.d.ts

/// <reference path="../typings/q/Q.d.ts" />

if(importScripts != undefined &&  WorkerGlobalScope == undefined 
        && typeof module !== 'undefined' && module.exports){

    // We're in a Node (child) process
    var Q = require("q")
}else{
    // We're in a web-worker
    importScripts('q');
}

我收到以下错误, 中对此进行了很好的解释:

error TS2300: Duplicate identifier 'Q'.

但是如果我用 import Q = require("q") 替换 var Q = require("q"),我会得到这个错误,因为 import 语句嵌套在 if 子句中而不是在脚本的顶层:

An import declaration can only be used in a namespace or module.

有没有办法要求 Q in 以便它与节点的 require() 和 web-worker 的 importScripts() 一起工作?

Is there a way to require Q in so that it works with both node's require() and web-worker's importScripts()?

您只需导入 Q 类型 ,然后 如果需要 则延迟加载 q .所以:

import _Q = require('q');
if(importScripts != undefined &&  WorkerGlobalScope == undefined 
        && typeof module !== 'undefined' && module.exports){

    // we're in a Node (child) process
    var Q:typeof _Q = require("q")
}else{

    importScripts('q');
}

更多

这在此处的延迟加载部分中有所介绍:https://basarat.gitbooks.io/typescript/content/docs/project/external-modules.html