将 moment.js 与 typescript 和 "module" 结合使用:"amd"

Using moment.js with typescript and "module": "amd"

我正在尝试使用来自打字稿 2.1.5

的 moment.js

我用 npm 安装了 moment :

npm install moment --save-dev

d.ts 文件包含在 moment.js 中,因此不需要通过 @typings 安装 但是当我编译我的项目时,出现以下错误:

error TS2307: Cannot find module 'moment'.

这是我为重现问题所做的简单测试。

repro.ts 文件

import * as moment from "moment";
const date = moment().format("YYYY");
console.log(date);

tsconfig.json 文件:

{
    "compilerOptions": {
        "module": "amd"
    }
}

如果我用 :

编译
.\node_modules\.bin\tsc

我收到错误。我注意到如果我以 commonjs 模块为目标( "module": "commonjs" in tsconfig )

如果我以 amd 模块为目标,使用 moment 的正确方法是什么?

您必须将 "moduleResolution": "node" 添加到 tsconfig.json 中的 compilerOptions

省略时,moduleResolution 默认为 classic 除非 modulecommonjs,这就是在 node_modules 中找不到模块的原因。

此外,这看起来像是 going to be fixed 在编译器的某个未来版本中。