【问题标题】:Import TypeScript namespaces (as in C#/.NET)导入 TypeScript 命名空间(如在 C#/.NET 中)
【发布时间】:2016-12-19 02:45:47
【问题描述】:

在我的 TypeScript 项目中,我使用分布在命名空间中的多个文件中的类和接口。就像我以前在 C#/.NET 中做的那样。


IDispatcher.ts

namespace Dispatcher {
    export interface IDispatcher {
        Dispatch(msg: string): Promise<string>;
    }
}

DispatcherImpl.ts

namespace Dispatcher {
    export class Dispatcher implements Dispatcher.IDispatcher {
        Dispatch(msg: string): Promise<string> {
            return new Promise<string>((resolve, reject) => {
                    resolve('result');
            });
        }
    }
}

Test.ts

namespace Test {
    export class Test {
        private dispatcher: Dispatcher.IDispatcher;

        constructor() {
            this.dispatcher = new Dispatcher.Dispatcher();
        }
    }
}

let testRun = new Test.Test();

一切都可以很好地编译为 JavaScript(使用 targetmodule = es6)。
但是当我运行 node test.js 时,我得到 错误

this.dispatcher = new Dispatcher.Dispatcher();
                      ^
ReferenceError: Dispatcher is not defined

当我尝试import DispatcherImpl 时,它指出File 'DispatcherImpl.ts' is not a module。使用require('DispatcherImpl.ts'),它只会解析为any,也无法按预期工作。

所以我希望 TypeScript 命名空间的行为类似于 .NET 命名空间。但情况似乎根本不是这样。 如何安排我的接口和类的正确方法以及其他类如何使用/导入它们?也许有办法让 TypeScript 编译器自动解析命名空间?

【问题讨论】:

  • 实际上展望未来,您不应该再使用命名空间了。在 ES6 中,每个文件都是一个模块。无论如何,您如何导入东西? ///reference?
  • Tahnks 的提示。实际上现在没有导入和引用路径,因为 TSC 可以正常工作。
  • 这完全取决于很多事情。我猜你的问题是不同的文件在编译时没有得到正确的顺序,然后 JS 找不到东西。尝试检查 tsconfig.json 中的配置
  • 这个话题已经在 Github 讨论过了:TypeScript#2159(C# 开发者的困惑 [close]),TypeScript#2956(导入命名空间的请求 [open ])。后者自 2015 年 4 月起开放,因此裸导入命名空间的可能性似乎很小(很快或根本不会)。

标签: typescript import namespaces


【解决方案1】:

Currently 在 TypeScript 中没有 includeimport 语句用于命名空间。

我在 tsconfig.json 中找到了使用 outFile 选项的解决方法:

"outFile": "test.js"

通过这种方式,所有 TypeScript 代码都被翻译成一个单独的 JavaScript 文件。
要以正确的顺序排列,每个 TypeScript 文件都必须定义其依赖关系,例如

/// <reference path="DataModel/Common.ts" />

【讨论】:

    猜你喜欢
    • 2018-01-05
    • 1970-01-01
    • 2016-03-27
    • 2016-09-30
    • 1970-01-01
    • 2020-10-22
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多