Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript error: Cannot find module 'moment'

I have a TypeScript React app using npx create-react-app --template typescript. When I run npm start, I get an error in one of my files:

TypeScript error in /<path>/App.tsx:
Cannot find module 'moment'.  TS2307

Import:

import moment from 'moment'

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "noImplicitAny": false,
    "experimentalDecorators": true
  },
  "include": ["src", "husky.config.js", "lint-staged.config.js"]
}

Using "moment": "^2.25.0" in package.json. Using npm.

Looking in the node_modules directory, I can see the moment package, and the package.json file says moment is on version 2.25.0

I've tried clearing npm cache, deleting node_modules and package-lock.json, reinstalling, importing like import * as moment from 'moment'.

Any ideas? This just randomly started happening today. Thanks in advance.

like image 590
John Avatar asked May 01 '20 05:05

John


People also ask

Can not find module in angular?

To solve the error "Cannot find module '@angular/core'", make sure you have installed all dependencies by running the npm install command, set the baseUrl option to src in your tsconfig. json file and restart your IDE and development server. Copied!

Can not find module or its corresponding type declarations?

The "Cannot find module or its corresponding type declarations" error occurs when TypeScript cannot locate a third-party or local module in our project. To solve the error, make sure to install the module and try setting moduleResolution to node in your tsconfig. json file.


2 Answers

Update

moment version 2.25.1 is released. This fixes the issue.

Old Answer

It's an issue of moment version 2.25.0,

https://github.com/moment/moment/issues/5486

Delete your package-lock.json and node_modules folder, replace this line of code in your package.json

"moment": "2.24.0",

note, remove the ^, else it will keep installing 2.25.0

then npm install

This should resolve the issue.

like image 186
Jplus2 Avatar answered Oct 01 '22 01:10

Jplus2


You have to install a package before actually using it in your code. So you can Install moment library using npm (node package manager)

npm install moment

and then import this library

import * as moment from 'moment'

Then you are good to go.

like image 32
chirag sorathiya Avatar answered Oct 01 '22 01:10

chirag sorathiya