使用带有typescript和"module"的moment.js: [英] Using moment.js with typescript and "module": "amd"
问题描述
我正在尝试使用打字稿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
,除非module
是commonjs
,这就是在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屋!