- Cannot find module that is defined in tsconfig `paths`
- 15 Answers 15
- Error cannot find module typescript
- # Cannot find module ‘X’ Error in TypeScript
- # Install the third-party module
- # Delete your node_modules and reinstall your dependencies
- # Make sure your import statements use consistent casing
- # Set moduleResolution to node in your tsconfig.json file
- # Conclusion
- Typescript — Cannot find module . or its corresponding type declarations
- 10 Answers 10
Cannot find module that is defined in tsconfig `paths`
I am trying to setup aliases for my mock server. Whenever I try to compile ts files, it returns error that it couldn’t find proper modules even though those are defined in tsconfig,json -> paths Folder structure:
├── server │ └── src │ └──/json ├── src │ └──/modules ├── tsconfig.json
< "compilerOptions": < "baseUrl": "./src", "experimentalDecorators": true, "jsx": "react", "lib": [ "dom", "es2015", "es2015.promise" ], "module": "commonjs", "moduleResolution": "node", "noImplicitAny": true, "noUnusedLocals": true, "esModuleInterop": true, "paths": < "@project/app/modules/*": [ "modules/*" ], "@project/server/data/*": [ "../server/src/json/*" ] >, "sourceMap": true, "target": "es5" >, "exclude": [ "node_modules", "tools" ] >
15 Answers 15
well, after suffering a few hours, I got a solution, I am using the ts-node package, and I got the same error Error: Cannot find module ‘@modules/logger’
You need to add ts-node configuration in the tsconfig.json file. You can get more infor at ts-node
Here is my tsconfig.json file look like
< "ts-node": < // Do not forget to `npm i -D tsconfig-paths` "require": ["tsconfig-paths/register"] >, "compilerOptions": < "lib": ["es5", "es6", "es7"], "target": "es2017", "module": "commonjs", "moduleResolution": "node", "rootDir": "src", "outDir": "build", "emitDecoratorMetadata": true, "experimentalDecorators": true, "esModuleInterop": true, "noImplicitAny": true, "strict": true, "resolveJsonModule": true, "allowJs": true, "sourceMap": true, "baseUrl": ".", "paths": < "@modules/*": ["src/modules/*"], "*": ["node_modules/*"] >, >, "include": ["src/**/*"] >
and here is my package.json
You need to install this package as a dependency of module alias npm i module-alias
this is the finest solution, tsconfig is a different beast than the resolution of node itself, so you need a thing to allow node recognize your shiny aliased paths, as it is shared in this answer: stackoverflow.com/a/69514947/1778979
Adding the tsconfig-paths dev dependency and tsconfig-paths/register allowed the path «aliases» to work under ts_node execution. No need for module-alias if that is all that is desired.
For this to work you will need to import the module-alias dependency in you entry file import ‘module-alias/register’; as stated in this article dev.to/larswaechter/path-aliases-with-typescript-in-nodejs-4353.
I faced the same issue. I tried many things and now i got a solution which works for me. I have an app and a library in my angular project. I want to use a library alias in my app.
I have following structure:
├── projects │ └── lib │ └── src │ └── lib │ └── lib-service.ts │ └── index.ts │ └── app │ └──tsconfig.app.json ├── tsconfig.json
In the tsconfig.json file in the root folder I have following paths defined:
There I access an index.ts file where I define the things I want to export. In my case the index.ts file has the following entry:
export * from './lib/lib-service';
Now I can access the LibService in components of the app with the help of the alias:
It is important to mention that this soloution don’t work if I add this entry to the tsconfig.app.json file. I think the IDE (in my case WebStorm) searches for aliases in the tsconfig.json file which is close to the root folder. So I extend the tsconfig.json in my tsconfig.app.json
Maybe you have to restart you IDE to remove the red underline of the import line.
I hope this solution works for you. You have to to a little bit more of setup work because you have to define the classes you want to export in the index.ts file. But in case of using libraries it make sense because you don’t want to make everything visible for other app.
app works like a cham! But typescript still complaining even after restarting the IDE as Error: Can’t find module.
@TaylorA.Leach Random thing, you can usually get rid of the red lines by restarting the TS server within VS code. cmd+shift+p type Restart TS Server
This should be in bold: Maybe you have to restart you IDE to remove the red underline of the import line.
After battling it for some time I figured it out you need to include all directories using tsconfig-paths in your main tsconfig.json . Working version of your tsconfig.json file could be
But this way it’ll include all folders in src even without the paths. in my project I had the same name for a folder in src like a library I included. And it was complaining as it tried to read the local folder when imported, not the package.
it worked for me with dev mode, but not with tsc build and then running node dist/index.js so I added «dist/*» to paths along with «src/*» and key is «@/*» and now it works.
My issue was that my tsconfig.app.json which extended my tsconfig.json was overriding the «baseUrl» option incorrectly. I removed it from the tsconfig.app.json so it did not have a «baseUrl» or «paths» . In the end, my tsconfig.json had the following compiler options:
The following tsconfig.json worked for me, allowing import < foo >from ‘@models’ etc for the associated index.ts barrel exports:
TypeScript path properties can reliably resolve typings-based URLs such as an interface.
The intended behaviour is to allow TypeScript to resolve type information [1]
Most us seem to be experiencing that a path pointing to an actual dependency wont always compile as we expect. This is apparently by design despite what the doc says:
Read this great breakdown by Mitchell Simoens — Why TypeScript Paths Failed Me
Found this after setting up @paths to my shared folders throughout the app. During compilation TS paths where breaking and actual builds were missing all sorts of modules. On a personal note this is a huge disappointment that TS can’t reliably resolve dependencies this way.
and add the mappings from your tsconfig.json paths to _moduleAliases in your package.json
As for the reasoning behind it, using «jsx»: «react» in conjunction with «module»: «commonjs» prevents you from being able to use absolute imports even though baseUrl and paths are configured correctly. A detailed discussion can be found in this issue.
When u use the bare variant with just tsconfig.json ( «typescript»: «^4.4.4» ) without any third party libraries:
You can easily define simple path resolver like this:
const Module = require("module"); const originalResolveFilename = Module._resolveFilename; const tsConfig = require("./tsconfig.json"); const Path = require("path"); const fs = require('fs'); if (!tsConfig.compilerOptions || !tsConfig.compilerOptions.baseUrl) throw "Compiler options Base URL (compilerOptions.baseUrl) is required in tsconfig.json."; const basePath = Path.resolve(tsConfig.compilerOptions.baseUrl, tsConfig.compilerOptions.outDir); //Inspired by https://github.com/dividab/tsconfig-paths but that one does not work with VS Code Module._resolveFilename = function (request) < if (tsConfig.compilerOptions && tsConfig.compilerOptions.paths[request] instanceof Array) < //Supports only without wildchars, but enough for our use const pathsTried = []; for (const reqPath of tsConfig.compilerOptions.paths[request]) < const modPath = Path.resolve(basePath, reqPath) + ".js"; if (fs.existsSync(modPath)) return modPath; pathsTried.push(reqPath); >throw "Module " + request + " not found, paths tried: " + pathsTried.join(", "); > const ret = originalResolveFilename.apply(this, arguments); return ret; >;
and than reference it from VS Code’s launch.json like this:
"configurations": [ < "type": "node", "request": "launch", "name": "Node.js", "runtimeArgs": ["-r", "./loader.js"], "program": "$/run.ts", "preLaunchTask": "tsc: build - tsconfig.json", "outFiles": [ "$/out/**/*.js" ] >]
It does not support patterns in paths but with this stub it can be added.
tsconfig.json should look like this:
at least for me tsc creates sub-folder in name of the root folder in out that’s why the 2 registrations.
Error cannot find module typescript
Last updated: Jan 20, 2023
Reading time · 3 min
# Cannot find module ‘X’ Error in TypeScript
The «Cannot find module or its corresponding type declarations» occurs for multiple reasons:
- Forgetting to install a third-party package or its type definitions.
- Having a glitched node_modules directory.
- Specifying an incorrect path to the module you are importing from.
- Setting the moduleResolution property to an incorrect value in tsconfig.json .
# Install the third-party module
If the module is a third-party module, make sure you have it installed.
Copied!npm install module-name
If the module has type definitions, make sure to install them as well.
Copied!npm install --save-dev @types/module-name
# Delete your node_modules and reinstall your dependencies
Try removing your node-modules directory and your package-lock.json file, re-run npm install and reload your IDE.
If you are on macOS or Linux, issue the following commands in bash or zsh .
Copied!# for macOS and Linux rm -rf node_modules rm -f package-lock.json rm -f yarn.lock # 👇️ clean npm cache npm cache clean --force # 👇️ install packages npm install
If you are on Windows, issue the following commands in CMD.
Copied!# for Windows rd /s /q "node_modules" del package-lock.json del -f yarn.lock # 👇️ clean npm cache npm cache clean --force # 👇️ install packages npm install
Make sure to reload your IDE as VS Code often glitches and needs a reboot.
# Make sure your import statements use consistent casing
Some operating systems like Windows treat file and directory names as case-insensitive.
However, macOS and Linux treat file and directory names as case-sensitive.
Make sure you haven’t misspelled the path to the module in your import statement.
Copied!import country > from './myFile'; import country > from './MyFile';
The two import statements do the same on Windows machines because file names on Windows are case-insensitive.
However, if you run this code on a Unix-like operating system like Linux or macOS, you would get an error, because they treat file names case-sensitively and these are 2 completely different files.
A best practice is to use the forceConsistentCasingInFileNames option in your tsconfig.json file.
Copied!"compilerOptions": "forceConsistentCasingInFileNames": true, // . > >
When the forceConsistentCasingInFileNames option is set to true , TypeScript will issue an error if you try to include a file by using a different casing from the casing of the file name on the disk.
For example, if you try to import from MyFile.ts , but the name of the file is myFile.ts , you’d get an error.
When this option is set to false , TypeScript follows the case sensitivity rules of the file system it’s running on.
This can be very confusing if some of the developers on your team use Windows machines and other Unix-like OS, because if you try to import myFile.ts by specifying MyFile.ts , it will be found on Windows, but not on macOS or Linux.
# Set moduleResolution to node in your tsconfig.json file
If that doesn’t help or TypeScript can’t locate your local modules, try setting moduleResolution to node in your tsconfig.json file.
Copied!"compilerOptions": "moduleResolution": "node", // 👇️ . rest > >
You can read more about classic vs node module resolution in the TypeScript docs.
If that doesn’t help, make sure the module you are trying to import is tracked by TypeScript.
It should be covered in your include array setting and not be present in the exclude array in your tsconfig.json file.
Copied!"compilerOptions": // . >, "include": ["src/**/*"], "exclude": ["node_modules", "src/**/*.spec.ts"] >
For example, if the module is out of the src directory whilst using the configuration from the code snippet, TypeScript wouldn’t be able to find it.
Make sure you haven’t excluded the module by adding it to your exclude array.
If your error message changes to «Could not find declaration file for module ‘module-name'», then TypeScript has located the module you are trying to import, but can’t find its type declarations.
If that is the case, check out my other article — Could not find declaration file for module ‘X’ Error.
If you got the error when using any of the following packages, click on the relevant article:
# Conclusion
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, install the module and try setting moduleResolution to node in your tsconfig.json file.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Typescript — Cannot find module . or its corresponding type declarations
I created a new project using create-react-app and yarn 2 in vs code. The editor throws errors while importing every installed library like this:
The project compiles and runs successfully but the errors are still there. When I change the file’s extension to .js and .jsx from.ts and .tsx, the errors disappear. How should I solve this problem for typescript files?
10 Answers 10
You need to install types for libraries you install. generally you should do:
npm install @types/libName // e.g. npm install @types/react-leaflet
Some times there’s no types available in DefinitelyTyped repo and you encounter npm ERR! 404 Not Found: @types/my-untyped-module@latest . You can do several things in this occasion:
1- Create a decs.d.ts file in root of your project and write in it:
declare module "libName" // e.g declare module 'react-leaflet'
2- Or simply suppress the error using @ts-ignore :
// @ts-ignore import Map from 'react-leaflet'
3- Or you can do yourself and others a favor and add the library types in DefinitelyTyped repo.
If it still doesn’t work, I firstly recommend that you use a recent version of Typescript. if you do, then close your editor, delete node_modules folder and install the dependencies again ( npm install or yarn install ) and check it again.