使用带有typescript和"module"的moment.js: [英] Using moment.js with typescript and "module": "amd"

查看:112
本文介绍了使用带有typescript和"module"的moment.js:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用打字稿2.1.5中的moment.js

I'm trying to use moment.js from typescript 2.1.5

我用npm安装了时刻:

I installed moment with npm :

npm install moment --save-dev

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

The d.ts file is included with moment.js so no install via @typings is required but when I compile my project I get the following error :

错误TS2307:找不到模块'moment'.

error TS2307: Cannot find module 'moment'.

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

Here is a simple test I made to repro the issue.

repro.ts文件

repro.ts file

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

tsconfig.json文件:

tsconfig.json file :

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

如果我使用:

.\node_modules\.bin\tsc

我得到了错误.我注意到,如果我定位commonjs模块(tsconfig中的"module":"commonjs"),编译效果很好

I get the error. I notice that the compilation is fine if I target commonjs module ( "module": "commonjs" in tsconfig )

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

What is the correct way of using moment if I target amd module ?

推荐答案

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

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

When omitted, moduleResolution defaults to classic unless module is commonjs, that's the reason your modules are not found in node_modules.

另外,在将来的某些发行版中,它看起来像是将要修复的的编译器.

Also, it looks like this is going to be fixed in some future release of the compiler.

这篇关于使用带有typescript和"module"的moment.js:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆