【问题标题】:typescript modules across files跨文件的打字稿模块
【发布时间】:2015-11-18 08:53:19
【问题描述】:

我正在尝试使用 typescript 获取一个简单的节点项目,并使用共享模块将代码分成两个单独的文件。但是遇到了一些问题!

1) FileReader.ts 在共享模块中定义 + 导出静态函数

var fs = require("fs");

export module Qbot {

    export class Utils {
        static read(filename: string) {
            var buf = fs.readFileSync(filename, "utf8");
            return data;
        }

    }

    Qbot.Utils.read("test");  // compiles OK

}

2) FileReader-spec.ts 一个单独的文件来尝试使用上述内容。

/// <reference path="./FileReader.ts" />

// should be in same module but TS compiler gives an error
module Qbot {
    var u = Qbot.Utils;  // ERR does not exist
    var data = Qbot.Utils.read("somefile.json");  // ERR cant find name
}

// outside the module? nope.
var data = Qbot.Utils.read("somefile.json");  // Utils doesnt exist

// this works but why the extra file thingy needed?
import something = require("./FileReader");
var filepath = "./topics.json";
var data = something.Qbot.Utils.read(filepath);

我是否需要始终导入额外的文件以“包含”导入模块,然后才能访问它们?任何有关如何实现这一目标的指示将不胜感激!

这个例子也只是试图在 Qbot.Utils 模块上调用一个静态函数(根据这个例子https://stackoverflow.com/a/13212648/1146785

谢谢!

【问题讨论】:

  • 更新我可以用export = Qbot解决这个问题

标签: module static typescript


【解决方案1】:

我是否需要始终导入额外的文件以“包含”导入模块,然后才能访问它们?任何有关如何实现这一目标的指示将不胜感激!

不要将内部模块与外部模块混用。只需使用外部模块。例如在你的情况下FileReader.ts

import fs = require("fs");

export class Utils {
    static read(filename: string) {
        var buf = fs.readFileSync(filename, "utf8");
        return data;
    }

}

Utils.read("test");  // compiles OK

【讨论】:

    猜你喜欢
    • 2015-07-15
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 2017-03-09
    • 1970-01-01
    相关资源
    最近更新 更多