How To Solve “Cannot find module ‘path'” Error in TypeScript

In using modules for fast coding in TypeScript, we may encounter the error “Cannot find module ‘path'”. The error occurs because we have not installed types for the node. To fix it, we need to install and check the configuration file tsconfig.json again. This article will go into detail about the cause and how to fix it, let’s get started.

Cause of “Cannot find module ‘path'” error in TypeScript

This error occurs because we have not installed the type for the node. If the module you need to use is written in TypeScript, then we need to install the type for this module. If not installed and proceeding to build the project, the error will happen as follows.

Cannot find module 'path' or its corresponding type declarations

The solution to fix this error

In order for this error not to appear, we need to install the type for the node, then check the configuration in the tsconfig.json file, and restart the IDE for the changes to take effect.

Install types for node

Because TypeScript needs types for modules, we need to install type, only JavaScript-written modules are not needed, so we run the following syntax to install.

npm i -D @types/node

Make sure you are in the project directory where you want to use the module and run the above installation syntax. After installation, if the error is not resolved, try restarting the IDE and TypeScript server.

Check the file tsconfig.json

If the above doesn’t fix the error, then maybe the configuration in the tsconfig.json file is wrong. Please make sure that the node has been added to the "types" array.

{
  "compilerOptions": {
    "types": ["node"]
  }
}

After you have edited the tsconfig.json file, you also need to proceed to restart the IDE and TypeScript server

Delete the node_modules folder

If the above two methods still do not fix the error, then only this last way, and I believe that this way you will fix the error. We will delete the node_modules folder and the package-lock.json file, then proceed to reinstall the deleted modules.

npm install

Run the above syntax to reinstall the deleted modules, and also restart the IDE and TypeScript server.

Summary

In conclusion, the error “Cannot find module ‘path'” in TypeScript occurs because we have not installed types for a module written in TypeScript. We can proceed with the installation, then check the configuration in the tsconfig.json file. If the error is still not fixed, then we should delete the module and install it again like new. Hopefully, with this article, you will quickly fix the error. Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *