简体   繁体   中英

Using moment.js with typescript and “module”: “amd”

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

I installed moment with npm :

npm install moment --save-dev

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 :

error TS2307: Cannot find module 'moment'.

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

repro.ts file

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

tsconfig.json file :

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

If i compile with :

.\node_modules\.bin\tsc

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

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

You have to add "moduleResolution": "node" to compilerOptions in tsconfig.json .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM