d.ts文件和nodejs需要具有相同名称的重复标识符错误

Gro*_*fit 2 javascript node.js typescript tsc

现在我确定问题是因为包含一个名为"Shared"的模块的d.ts文件,以及一个require语句,如果在NodeJS环境中使用它,则该语句包含一个同名变量.

// shared.d.ts
declare module Shared { ... }

// other_module.ts
/// <reference path="shared.d.ts"/>
if(require) { var Shared = require("shared"); }
export class Something {
    public someVar = new Shared.SomethingElse("blah");
}
Run Code Online (Sandbox Code Playgroud)

因此,当我编译other_module.ts(实际上是很多单独的文件)时,它告诉我Shared是一个重复的标识符,我可以理解,因为TS认为Shared是一个模块,但后来被告知它是require的返回.

这里的问题是模块的输出需要与nodeJS的require系统兼容,所以在这种情况下,当需要other_module时,它将在它自己的范围内并且不知道Shared.SomethingElse所以需要需要因此内部模块other_module将是能够访问共享库,但在浏览器环境中,它将Shared.SomethingElse通过全局范围获取.

如果我删除引用然后文件不会编译,因为它不知道Shared,如果我删除模块加载到nodejs(var otherModule = require("other_module"))时,它会抱怨它不知道Shared.有没有办法解决这个问题?

bas*_*rat 6

首先是错误

重复的识别码,因为你必须Sharedshared.d.ts在+ other_module.ts.

FIX A,全部是外部的

如果你想使用amd/ commonjsie.外部模块,你需要使用import/require(var/require不像你在做).使用an import创建一个新的变量声明空间,因此您不再Shared从中污染全局命名空间other_module.ts.简而言之 :

// shared.d.ts
declare module Shared { 
   export function SomethingElse(arg:string):any;
}
declare module 'shared'{ 
    export = Shared; 
}
Run Code Online (Sandbox Code Playgroud)

和类型安全的导入:

// other_module.ts

/// <reference path="shared.d.ts"/>
import Shared = require("shared"); 

export class Something {
    public someVar = new Shared.SomethingElse("blah");
}
Run Code Online (Sandbox Code Playgroud)

FIX B,就像你一样,但你需要使用不同的名称

如果本地范围是全局范围,则在本地内部other_module不使用该名称.我建议你只使用外部的所有地方并使用和浏览器编译节点,如修复A所示,但如果你必须在这里修复编译.Sharedcommonjsamdother_module.ts

// other_module.ts
/// <reference path="shared.d.ts"/>
var fooShared: typeof Shared;
if(require) {  fooShared = require("shared"); }
else { fooShared = Shared; } 
export class Something {
    public someVar = new fooShared.SomethingElse("blah");
}
Run Code Online (Sandbox Code Playgroud)