Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js + TypeScript. Cannot find name moment

I develope web application with knockout in VisualStudio. I just installed knockout via bower, included d.ts file in project, included script to html page and now i can get access to ko.

Now i try to use moment.js. Like with knockout: install, include d.ts, include script to page and i get an error cannot find name 'moment'. Adding reference to d.ts does not help, import * as moment from 'moment' get an error can not find module moment.

I know that it's a stupid problem, but i can't fix it. What am i doing wrong?

like image 206
user3272018 Avatar asked May 21 '16 09:05

user3272018


2 Answers

What I'd recommend is using some tool for managing your definitions. Some popular options (you don't need both, just pick one):

  1. tsd - npm i -g tsd
  2. typings - npm i -g typings

These work in a similar fashion as package managers. You can install your definitions like npm/bower installs your dependencies.

Once you have one of these installed, go to your project and install moment + its definition

npm install moment --save

And one of these:

tsd install moment --save
typings install moment --save --ambient

Both of these will create a folder with your definitions in it (both call it typings), and both have an "umbrella" definition file in it, which you should reference in the entry point of your application (first is for tsd, second for typings):

/// <reference path="typings/tsd.d.ts" />
/// <reference path="typings/index.d.ts" />

After this is done, you can use moment (or any other module) as you would:

import * as moment from 'moment'
moment.isDate("I'm not a date")

I suggest checking out these:

https://github.com/DefinitelyTyped/tsd
https://github.com/typings/typings

like image 89
Balázs Édes Avatar answered Sep 18 '22 12:09

Balázs Édes


In my case, finally get this error solved by doing the following:

  1. Adding this option "allowSyntheticDefaultImports": true, in the compilerOptions section of the tsconfig.json file (EDITED: As the moment doc. sais in the Note: If you have trouble importing moment, try add "allowSyntheticDefaultImports": true in compilerOptions in your tsconfig.json file.)
  2. Also add "moduleResolution": "node" in the same compilerOptions section. (Found this option looking around the web)
  3. Importing moment module like this import * as moment from 'moment';
like image 42
Raúl Otaño Avatar answered Sep 18 '22 12:09

Raúl Otaño