【问题标题】:Typescript Import External Module in Internal ModuleTypescript 在内部模块中导入外部模块
【发布时间】:2014-10-16 17:58:30
【问题描述】:

我需要一些关于 Typescript 以及如何在内部模块中使用外部模块的帮助。

我想将我所有的 ViewModel 代码逻辑存储在 ViewModels 内部模块中。

** HomePageViewModel.ts **

module ViewModels {
export class HomePageViewModel {
    constructor() {
        console.log('Creating HomePageViewModel');
    }

    public SayHello(): void {
        console.log('Hello from HomePageViewModel');
    }
}
}

** ViewModelFactories **

public static CreateHomePageViewModel(): ViewModels.HomePageViewModel {
    return new ViewModels.HomePageViewModel();
} 

这工作正常,我可以编译并且在执行时一切正常。

现在,如果我在 HomePageViewModel 中添加一个导入(例如淘汰赛)

import ko = require('knockout');

Typescript 不再编译。 ViewModelFactories 代码在 Views 下带有下划线,并通知我它“找不到符号视图”。

如何从 ViewModel 模块中访问淘汰模块?

【问题讨论】:

    标签: knockout.js module typescript amd


    【解决方案1】:

    基本上,您不能混合使用两种模块类型。

    一旦您需要另一个外部模块,您的内部模块就会变成外部模块。 您必须以“内部”方式访问淘汰赛:将其作为 <script> 导入到您的起始 HTML 文件中(正如您可能已经为其他文件所做的那样),然后使用全局 ko 变量。

    另一种解决方案是使您的模块外部化。

    【讨论】:

    【解决方案2】:

    您需要获取带有“ko.xxxxxx”定义的“knockout.d.ts”文件(或类似文件)。您可以从nugetgithub 获得它。 之后你就可以写了,例如

    var observable = ko.observable<number>(100);
    

    在您的 TypeScript 代码中。当然,您仍然需要在您的页面上包含“knockout.x.x.x.js”文件。

    您可能应该使用 namspase,如 TypeScript Documentation 所述:

    不必要的命名空间

    如果您要将程序从内部模块转换为外部模块,很容易得到如下所示的文件: 形状.ts

    export module Shapes {
        export class Triangle { /* ... */ }
        export class Square { /* ... */ }
    }
    

    这里的顶层模块Shapes 无缘无故地把Triangle 和Square 包起来了。这对于您的模块的使用者来说是令人困惑和烦人的: shapeConsumer.ts

    import shapes = require('./shapes');
    var t = new shapes.Shapes.Triangle(); // shapes.Shapes?
    

    【讨论】:

    • 我已经有了 knockout.d.ts 文件。如果我写“导出模块 ViewModels”。一切正常,我可以导入淘汰赛,但是该模块被视为外部模块,我需要它来访问它。它还会导致模块不加载定义该模块的其他文件。
    • 我检查了'typescript.codeplex.com/…'文档,可能你需要指定敲除的相对路径,比如'import shapes = require('./shapes');'在上述文档中?
    • 也许您应该使用导入名称来访问淘汰赛? '进口淘汰赛=要求('淘汰赛'); var v = knockout.ko.observable();'?
    【解决方案3】:

    您的 HomePageViewModel 是在 ViewModels 模块中定义的,而不是在 Views 模块中。

    public static CreateHomePageViewModel(): ViewModels.HomePageViewModel {
        return new ViewModels.HomePageViewModel();
    } 
    

    【讨论】:

    • 感谢您发现这一点,但不幸的是这不是问题:(
    猜你喜欢
    • 2015-08-11
    • 2015-06-21
    • 2014-04-05
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    相关资源
    最近更新 更多