Typescript paths cannot find module

‘Cannot find module that is defined in tsconfig `paths`

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.

Solution 2: [2]

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:

Solution 3: [3]

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

Solution 4: [4]

The following tsconfig.json worked for me, allowing import < foo >from ‘@models’ etc for the associated index.ts barrel exports:

Solution 5: [5]

and add the mappings from your tsconfig.json paths to _moduleAliases in your package.json

Читайте также:  Inset text shadow in css

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.

Solution 6: [6]

TypeScript path properties can only 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.

Solution 7: [7]

I put it both in webpack resolve alias and the tsconfig paths and it worked that way 🙂

Solution 8: [8]

There are some issues with path, for example if you set the path to the root let us say: @root/src and in src there is no index.ts that has a default, then this might fail.

It’s a bit tricky per what I found.

Solution 9: [9]

When u use the bare variant with just tsconfig.json ( «typescript»: «^4.4.4» ) without any third party libraries:

Solution 10: [10]

Check angular.json file if its «build» -> «options» config has «tsConfig» option set as your changed tsconfig file.

The above one is my angular.json file, and I configured it to use tsconfig.app.json. In this case, «paths» should be added in tsconfig.app.json file.

Solution 11: [11]

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.

Читайте также:  Input file html bootstrap

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Источник

How to fix jest + typescript + absolute paths (baseurl) gives error: cannot find module?

When using Jest with Typescript and absolute paths (baseUrl), you may encounter the error «Cannot find module». This issue occurs because Jest doesn’t understand the absolute paths defined in the Typescript configuration, resulting in the failure to locate and import the necessary modules.

Method 1: Using moduleNameMapper in Jest Config

To fix the «Cannot find module» error when using Jest with Typescript and Absolute paths (baseUrl), you can use the «moduleNameMapper» configuration in your Jest config file. Here are the steps to do it:

  1. Open your Jest config file (usually named «jest.config.js» or «jest.config.ts»).
  2. Add the «moduleNameMapper» configuration to the file:
module.exports =  // other Jest configurations. moduleNameMapper:  "^@/(.*)$": "/src/$1" > >;

Here, we’re telling Jest to map any module that starts with «@/» to the «src» directory in our project. You can customize this to match your own project’s directory structure.

Here’s an example of how to use the «moduleNameMapper» configuration with Typescript and Absolute paths:

// src/utils/myUtil.ts export const myUtil = () =>  return "Hello World"; >;
// src/index.ts import  myUtil > from "@/utils/myUtil"; console.log(myUtil());
// jest.config.js module.exports =  // other Jest configurations. moduleNameMapper:  "^@/(.*)$": "/src/$1" > >;
// src/__tests__/index.test.ts import  myUtil > from "@/utils/myUtil"; describe("myUtil", () =>  it("returns 'Hello World'", () =>  expect(myUtil()).toBe("Hello World"); >); >);

In this example, we have a Typescript project with a «src» directory that contains a «utils» directory with a «myUtil.ts» file. We’re using an Absolute path («@/») to import the «myUtil» function in our «src/index.ts» file. Finally, we have a Jest test file that imports the «myUtil» function using the same Absolute path.

By using the «moduleNameMapper» configuration in our Jest config file, we’re telling Jest to resolve the Absolute path to the correct file path. This allows us to use Absolute paths in our project without getting the «Cannot find module» error.

Method 2: Creating a Custom Jest Transform Script

If you are using Jest with Typescript and have configured absolute paths using baseUrl in your tsconfig.json file, you may encounter an error like this:

Cannot find module '@my-module' or its corresponding type declarations.

This is because Jest does not understand the baseUrl configuration. To fix this error, you can create a custom Jest transform script.

Step 1: Install Required Packages

First, you need to install the required packages:

npm install --save-dev ts-jest @types/jest

Step 2: Create a Custom Jest Transform Script

Create a file called jest.transform.js in the root of your project with the following content:

const ts = require('typescript'); const  pathsToModuleNameMapper > = require('ts-jest/utils'); const  compilerOptions > = ts.readConfigFile('./tsconfig.json', ts.sys.readFile); const  baseUrl, paths > = compilerOptions; const moduleNameMapper = pathsToModuleNameMapper(paths,  prefix: '/' >); module.exports =  process(src, filename)  const moduleName = moduleNameMapper[filename]; if (moduleName)  const newPath = moduleName.replace('/', ''); const newSrc = `module.exports = require('$newPath>');`; return newSrc; > return src; >, >;

This script reads the tsconfig.json file, extracts the baseUrl and paths configurations, and creates a moduleNameMapper object that maps module names to file paths. Then, it exports a process function that replaces the module name with the file path in the source code.

Step 3: Configure Jest

In your jest.config.js file, add the following configuration:

module.exports =  // . transform:  '^.+\\.tsx?$': 'ts-jest', '^.+\\.jsx?$': 'babel-jest', '^.+\\.js?$': '/jest.transform.js', >, moduleNameMapper:  . moduleNameMapper, '\\.(css|less|scss)$': 'identity-obj-proxy', >, // . >;

This configuration tells Jest to use the custom transform script for .js files, and also includes the moduleNameMapper object created in the previous step. The last line maps CSS/LESS/SCSS files to an identity object, which is useful for testing components that import styles.

Step 4: Test Your Code

Now you can run your Jest tests and verify that the Cannot find module error is gone. For example:

That’s it! You have successfully fixed the Jest + Typescript + Absolute Paths (baseUrl) error by creating a custom Jest transform script.

Method 3: Modifying the Typescript Compiler Options

To fix the error «Cannot find module» while using Jest with Typescript and Absolute paths (baseUrl), you can modify the Typescript Compiler Options in your tsconfig.json file. Here are the steps:

 "compilerOptions":  "baseUrl": ".", "paths":  "@/*": ["src/*"] > > >
npm install tsconfig-paths --save-dev
 "jest":  "moduleNameMapper":  "^@/(.*)$": "/src/$1" >, "transform":  "^.+\\.tsx?$": "ts-jest" >, "globals":  "ts-jest":  "compilerOptions":  "baseUrl": ".", "paths":  "@/*": ["src/*"] > > > > > >
import 'tsconfig-paths/register';

Now you should be able to use absolute paths in your Jest tests without getting the «Cannot find module» error. For example, if you have a file located at src/utils/myUtil.ts, you can import it in your test file like this:

import  myUtil > from '@/utils/myUtil';

Note that the «@» symbol in the import path is mapped to the «src» directory in your tsconfig.json file.

Источник

Оцените статью