Moment.js + TypeScript. Cannot find name moment
In my case, finally get this error solved by doing the following:
- Adding this option
"allowSyntheticDefaultImports": true,
in thecompilerOptions
section of thetsconfig.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.
) - Also add
"moduleResolution": "node"
in the samecompilerOptions
section. (Found this option looking around the web) - Importing moment module like this
import * as moment from 'moment';
This seems to solve the problem for me (the other solutions in this thread didn't work):
import * as moment from 'moment/moment.js';
I still seem to be getting the correct typescript definitions even referencing the js file directly. I suspect the reason is that the 'moment' folder under node_modules does not have an index.js file but I'm not a typescript typings/compiler expert.
I had the same error today. The fix was to downgrade the "moment" package from "2.25.0" to "2.22.1" in package.json
My application is an angular 8 version and "typescript": "3.5.3
What I'd recommend is using some tool for managing your definitions. Some popular options (you don't need both, just pick one):
tsd
-npm i -g tsd
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