如果 TypeScript 包含 require,则无法找到模块

TypeScript cannot find module if it contains a require

我正在尝试了解如何正确使用 TypeScript 和经典 JS 节点模块。

我建立了一个非常基本的项目,具有以下文件架构:

.
├── index.ts
├── lodash.d.ts
├── module.ts
└── node_modules
    └── lodash

lodash 已与 npm 一起安装。由于它似乎没有提供打字信息,我写了一个基本的 d.ts 文件,只描述了一个功能,只是为了取悦 tsc 并避免不知道 lodash.

的错误

lodash.d.ts

declare module "lodash" {
  export function reverse(array: any[]): any[];
}

在我的 module.ts 文件中,我使用 require 导入 lodash 并在模块上公开一个函数,我在 index.ts 文件中使用它。

module.ts

/// <reference path="./lodash.d.ts" />

import _ = require('lodash');

module FooModule {
  export function foo() {
    return _.reverse([1, 2, 3]);
  }
}

index.ts

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

let a = FooModule.foo();
console.log(a);

问题是 tsc(以及 VS Code)告诉我找不到名称 FooModule

$ tsc index.ts --module commonjs -outDir build
index.ts(3,9): error TS2304: Cannot find name 'FooModule'.

但是,如果我从 module.ts 中删除 import _ = require('lodash');,它会正常工作(除了 _ 变量现在未定义这一显而易见的事实)。

我是不是做错了什么require

您正在混合使用内部模块和外部模块。如果您在 .ts 文件中使用顶级导入或导出语句,文件 本身 会自动被视为外部模块,其内容都是该模块的一部分(require 是一个导入语句)。

如果将内部模块放入外部模块(modulenamespace 关键字),则实际上是对模块内容进行了双重包装。那可不好。

举个例子:

module.ts

import _ = require('lodash');

module FooModule {
    export function foo() {
        return _.reverse([1, 2, 3]);
    }
}

函数 foo 现在有效 module.FooModule.foo 如果您从外部模块 module 导出内部模块 FooModule:

export module FooModule {
    // ...
}

但是,这不好