【问题标题】:Typescript - internal module cannot be imported - unexpected behavior打字稿 - 无法导入内部模块 - 意外行为
【发布时间】:2012-12-28 00:29:53
【问题描述】:

我有 2 个模块分布在 2 个文件中:

--App.Tools.Utils.ts

export interface ILogger {
    log: (msg: string) => void;
}

module App.Tools.Utils {     


    export class Logger implements ILogger { ... }

    export function someFunction(){ ... }
}

然后在第二个文件中导入模块:

--App.Routers.ts

 /// <reference path="App.Tools.Utils.ts" />
 module App.Routers { 

    import Utils = App.Tools.Utils;  //ERROR: A module cannot be aliased to a non-module type        

}

我最终发现解决方案是将 ILogger 界面移动到 App.Tools.Utils 模块内以解决错误。起初它是有道理的,我认为编译器不会让我导入模块,因为 Logger 类实现了一个不包含在模块中的接口。为了测试,我将 ILogger 接口移到模块内部(错误已解决),然后在模块外部添加了一个任意接口(模块内部或任何地方都没有使用的接口),然后错误返回..

export interface INeverUsed { } //generates same error

module App.Tools.Utils {     

    export interface ILogger {
       log: (msg: string) => void;
    }

    export class Logger implements ILogger { ... }

    export function someFunction(){ ... }
}

查看生成的 JS,在模块外部添加接口会生成一个 define(["require", "exports"] 包装器,这会导致尝试在另一个文件中导入 App.Tools.Utils 模块时出错。删除接口会删除 define 包装器并解决错误。

这是预期的行为吗?当我在同一个文件中但在模块外部定义接口时,为什么模块突然“关闭”对我来说毫无意义,尤其是在模块内部甚至没有使用该接口的情况下。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    因为您在接口上使用了export 关键字,所以编译器将文件视为模块。

    如果你去掉界面上的export关键字,它应该可以工作:

    interface ILogger {
        log: (msg: string) => void;
    }
    
    module App.Tools.Utils {     
        export class Logger implements ILogger { 
            log(msg: string) { }
        }
    
        export function someFunction(){  }
    }
    

    和

    ///<reference path="game.ts" />
    
    module App.Routers { 
        import Utils = App.Tools.Utils; // works      
    }
    

    【讨论】:

    • 感谢您的回复。一旦我测试了我做出的直到以后我才能测试的假设,我就会将其标记为答案。假设是,如果我将“导出”留在界面上并将导出添加到 App.Tools.Utils 模块,错误应该会消退。我的理由是,如果该文件被视为全局模块,那么“导出模块 App.Tools.Utils”应该对另一个文件仍然可见。
    • 我也试过了 - 但它似乎没有解决它。如果我在这一点上错了,请告诉我。
    • 你是对的,这并不能解决错误。此外,模块上的“导出”会使模块内的 ILogger 无效,除非该接口也被导出。
    猜你喜欢
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多