The error message "Module not found" has appeared while searching from the root directory in VS Code

Struggling to resolve a module import issue in Visual Studio Code:

https://i.sstatic.net/33tzW.png

A demonstration of this problem can be found in a sample repository with the following directory structure:

➜ tree -I node_modules
.
├── README.md
├── packages
│   ├── jsx
│   │   └── jsx.jsx
│   ├── tjs
│   │   └── tjs.js
│   ├── tscript
│   │   └── tscript.js
│   └── tsx
│       └── tsx.tsx
├── src
│   ├── entry.ts
│   └── localjs.js
└── tsconfig.json

Attempting to make this setup compatible with babel-typescript, but it seems the root issue lies within VSCode, hence it's excluded from the sample.

Various permutations of the paths in tsconfig.json have been tested:

    "paths": {
      "*": [
        "*",
        "packages/*",
        "packages/*/index.tsx",
        "packages/*/index.jsx",
        "packages/*/index.js"
      ],
      "$1": [
        "packages/$1/$1"
      ],
      "~/*": [
        "packages/*"
      ],
      "~/$1": [
        "packages/$1/$1"
      ],
      "*/$1": [
        "*/$1/$1",
        "packages/$1/$1",
        "*/packages/$1/$1"
      ]
    }

The handbook offers limited insight into this issue.

Answer №1

A suggestion was made by Wex in their answer to rename your files to have the basename index with the appropriate extension and use the mapping "*"*: ["*", "packages/*"]. However, you expressed a preference to avoid renaming the files. Apart from avoiding renames, having many files named index.<some_extension> can be distracting when working. It requires extra effort to differentiate between files with similar basenames by looking at the directory structure or typing out the full path. This can be bothersome and time-consuming.

Let's address some obstacles first. There's no indication that ~ and $1 have any special treatment within paths. Checking the source code of tsc didn't reveal any handling of such patterns. It seems that these symbols are not treated as special characters. Also, disregarding extensions for now, your desired mapping seems to be

packages/<package_name>/<package_name>.ext
, which includes the package name twice. Although setting a mapping like "*": ["packages/*/*.ext"] might seem logical, TypesScript does not allow this due to the presence of two asterisks in the mapping, resulting in an error from tsc.

Utilize package.json

To avoid the renaming issue, consider adding a package.json to each package with a "main" field pointing to the desired entry file. For example, packages/jsx/package.json could contain:

{
  "main": "jsx.jsx"
}

By providing similar files for all packages, you can simplify the configuration to:

"baseUrl": "",
"paths": {
  "*": ["packages/*", "*"]
},

Alternatively, you can use "baseUrl" to specify your packages and omit "paths" entirely:

"baseUrl": "packages/",

Ensure the package.json files are linted as any syntax errors will be disregarded by tsc.

Include index Files for Reexporting

Another approach is to use index files that simply reexport the desired entry files of your packages. The existing files would remain, but they would be referenced by these index files. For example, packages/tsx/index.ts could contain:

export { default } from "./tsx";

If all packages have a default export, they can follow this pattern. For packages with multiple exports wanting to reexport everything, you can use:

export * from "./myModule"; 

By implementing this for all packages, you can meet the "*": ["*", "packages/*"] mapping requirement without renaming any files.

In a comment, you mentioned using tools like Barrelsby to generate index files. Consider the impact on development, as these generated files would coexist with manually authored files. If adding index files, aim for simplicity without relying on code generators.

Individually Map The Packages

If previous methods are impractical for your project, consider providing individual mappings for each package:

"paths": {
  "jsx": ["packages/jsx/jsx.jsx"],
  "tjs": ["packages/tjs/tjs.js"],
  "tscript": ["packages/tscript/tscript.js"],
  "tsx": ["packages/tsx/tsx.tsx"],
},

You could also set "baseUrl": "packages/" and update paths accordingly to reduce verbosity while still needing one mapping per package.

Answer №2

One issue to note with the current version of your tsconfig.json is the usage of include: [], which means no code will be matched by your configuration!

There doesn't seem to be any examples of using the $1 pattern in the way it's used in your sample configuration. Additionally, it seems that what you're attempting may not be possible, as indicated by some research findings (refer to: #5039). Is it feasible for you to rename {package}/{package}.jsx to {package}/index.jsx? If so, your paths configuration could be easily modified to:

    "paths": {
      "*": ["*", "packages/*"]
    },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing process.env in TypeScript can be a bit tricky as dot notation is not effective for accessing its properties

When I set my scripts to: "start": "NODE_ENV=development nodemon dist/Server.js", I am encountering an issue when trying to access NODE_ENV in my code. Both dot and bracket notation return undefined: The dependencies in my project are: "@types/node": "^8. ...

The class instances are not invoking the decorators

I'm experiencing issues with my decorators. It seems that the decorators are not being invoked on every instance of the class. While I understand that decorators are called during declaration time, I am wondering if there is a way to call them for eac ...

Setting up Next Js to display images from external domains

Encountering an issue with my next.config.js file while working on a project with Next.js in TypeScript. This project involves using ThreeJs, @react-three/fiber, and @react-three/drei libraries. Additionally, I need to include images from a specific public ...

Ways to retrieve root context within a Vue Composition API in Vue 3.0 + TypeScript

Looking to develop a TypeScript wrapper function that can trigger toast notifications using a composition function, following the guidelines outlined in Vue 3.0's Composition API RFC. In this instance, we are utilizing BootstrapVue v2.0 for toast not ...

Display or Conceal Multiple Divisions Using Angular 2

I am looking to implement a functionality using Li lists to toggle the visibility of multiple divs in Angular 2. Initially, all divs on the page will be visible. When viewing on a smaller screen, I want to hide some divs and show a specific div when a cor ...

Typescript types can inadvertently include unnecessary properties

It seems that when a class is used as a type, only keys of that class should be allowed. However, assigning [Symbol()], [String()], or [Number()] as property keys does not result in an error, allowing incorrect properties to be assigned. An even more curio ...

Typescript typings for child model/collection structures

I have encountered an issue while trying to implement a Model/Collection pattern with various typings. Both the Model and Collection classes have a method called serialize(). When this method is called on the Collection, it serializes all the Model(s) with ...

PrimeNG's Angular component pTree TreeNode

Is there a way in Angular to retrieve the positions of nodes within a TreeNode hierarchy based on their display order? I have data structured as TreeNode objects, which include children that can branch off further. How can I access these nodes according t ...

Angular - The filter method cannot be used on Observables

I have a database with users who need to complete unique homework sessions. Each homework session has its own identifier, name, date, and other details. After fetching all the user's homework from the database, it is stored in a private variable call ...

Error when compiling with Component Lab's Autocomplete function for SVG Icons in Material UI

Upon running my project on the browser, I encountered the following error: Error message: ./node_modules/@material-ui/lab/esm/internal/svg-icons/Close.js Attempted import error: 'createSvgIcon' is not exported from '@material-ui/core/utils ...

Using the Vue.js Compositions API to handle multiple API requests with a promise when the component is mounted

I have a task that requires me to make requests to 4 different places in the onmounted function using the composition api. I want to send these requests simultaneously with promises for better performance. Can anyone guide me on how to achieve this effic ...

Calculate the minimum, maximum, and average values within an array containing nested elements

I want to calculate the min, max, and average values for nested data that already have these values precalculated. Essentially, I'm looking for the average of averages, min of min, and max of max. I have a large dataset that includes the min, max, an ...

Utilize TypeScript to import a JSON file

I am trying to incorporate a JSON file using TypeScript, which contains data about different regions in Italy along with their respective capitals. Here is a snippet of the data: { "italia": [ { "regione": "Abruzzo", "capoluoghi": [ ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

Vue 3 app encountering error due to element having an 'any' type implicitly

I want to incorporate lucidev icons into my component, but I am fairly new to typescript. You can find the lucidev icons here: https://github.com/lucide-icons/lucide <template> <component :is="icon" /> </template> <script ...

Next.js 13 app directory experiences 404 Not Found error due to dynamic routing issues

I recently built a straightforward to-do app using Next.js 13 paired with TypeScript. The process involved creating an array of objects, each comprising an id string and a name string. Subsequently, I iterated through the list and showcased the names withi ...

Creating a digital collection using Vue, Typescript, and Webpack

A short while back, I made the decision to transform my Vue project into a library in order to make it easier to reuse the components across different projects. Following some guidelines, I successfully converted the project into a library. However, when ...

What is the process for obtaining the feedback from a new StepFunctionsStartExecution operation using AWS CDK?

Task Explanation: Iterate through the children in Step Function 1 Forward each JSON object to Step Function 2 Upon completion of Step Function 2, a response is obtained from an external API Utilize this API response within Step Function 1 Visual Represen ...

how to use all parameters except the first one in TypeScript

Is there a way to reference one function's parameter types in another function, but only use a subset of them without repeating the entire list of parameters? //params of bar should be same as foo, except p1 should be a different type function foo(p1 ...

Problem with timing in token interceptor and authentication guard due to injected service

Currently, I am facing an issue where I need to retrieve URLs for the auth service hosted on AWS by reading a config.json file. In order to accomplish this, I created a config service that reads the config file and added it as a provider in app.module. Eve ...