Issue with auto-completion not working for Typescript module imports in a nested project architecture or npm workspaces

My project has a complex setup with multiple distributed npm packages that have dependencies on each other. I've tried to simplify the structure as much as possible. The setup is structured like this (each subproject having its own package.json):

Project-root:
- package.json*
- /apps: - app1
         - app2
- /common
- /libs: - lib1
         - lib2

Apps: Each app stands alone and utilizes all libs and common, each with its own package.json

Common: Used for shared components, specifically within apps (depending on all libs)

Libs: Private npm packages utilized in other projects and in apps/common, work in progress so they are used/included via npm-workspaces/git clone. Added via npm install by workspaces

The issue I am facing is that TypeScript/tsc throws error ts(2307) in all classes within the "common" module.

import { BarInterface } from '@mynamespace/lib1/foo';

Cannot find module '@mynamespace/lib1/foo' or its corresponding type declarations.

Everything functions as intended and development/build processes run without errors, but Visual Studio Code/IntelliSense and/or tsc cannot recognize the import statements provided in common. Therefore, auto-completion is not available, which is crucial as the project should be easily accessible for new developers.

* package.json (root):

{
  "name": "main-project",
  "workspaces": [
    "./apps/*",
    "./libs/*",
    "./common"
  ]    
}

* package.json (lib):

{
  "name": "@mynamespace/lib1",
  "exports": {
    "./foo": "./src/foo/index.ts",
  },   
}

* package.json (common):

{
  "name": "main-project-common",
  "exports": {
    "./bar": "./src/bar/index.ts",
  },
  "dependencies": { 
    "@mynamespace/lib1": "^1.0.0"
    "@mynamespace/lib2": "^1.0.0"
  }   
}

* package.json (app1):

{
  "name": "app1",
  "exports": {
    "./bar": "./src/bar/index.ts",
  },
  "dependencies": { 
    "@mynamespace/main-project-common": "file:../../common"
  }   
}

All tsconfig.json files have the following configuration:

{
  "compilerOptions": {
    // Compiler options here
  },
  "include": ["src/**/*.ts", "global.d.ts"],
  "exclude": []
}

vite.config.js

import { defineConfig } from 'vite';
import path from 'path';

// Vite config
export default defineConfig({
  build: {
    target: 'esnext',
    lib: {
      entry: path.resolve(__dirname, 'src/index.ts'),
      formats: ['es'],
    },
    rollupOptions: {
      external: /^lit/,
    },
  },
});

Am I missing something or is the setup too complex or some sort of anti-pattern not supported by TypeScript?

Answer №1

After some investigation, I identified the root cause of the issue. It turns out that I forgot to include the module declaration for the common-module.

To resolve this issue, I created a new file named global.d.ts in the /common directory with the necessary content.

declare module '*';

It is crucial to complete this step for every typescript module in the project.

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

How can we retrieve the target element for an 'onSelectionChange' DOM event in Angular 6?

When using Angular 6, I want to retrieve the "formControlName" of the corresponding element whenever the selection changes. HTML <mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid"> <mat-select ...

What is required to run npm rebuild node-sass --force following each instance of a `yarn add` command?

As I attempt to set up the isemail npm library, everything appears to be going smoothly. However, when I execute yarn start:dev, which essentially runs "npm run build:dev && ./scripts/gendevconfig.sh && cross-env BABEL_DISABLE_CACHE=1 NODE_ ...

How to resolve the issue of a missing package.json file

Hello, I am encountering an issue while trying to remove an npm package in my terminal. The warning message that appears is: npm WARN saveError ENOENT: no such file or directory, open '/Users/liantonypozo/package.json' npm WARN enoent ENOENT: no ...

Having difficulty in fetching npm scoped artifacts for download

Following an update to version 5.1.3, our npm repository no longer allows the downloading of npm scoped artifacts. npm install @angular/core npm ERR! Linux 3.10.0-514.2.2.el7.x86_64 npm ERR! argv "/usr/bin/node" "/bin/npm" "install" "@angular/core" npm ER ...

Leveraging the power of literal types to choose a different type of argument

My API is quite generic and I'm looking for a typed TypeScript client solution. Currently, my code looks like this: export type EntityTypes = | 'account' | 'organization' | 'group' export function getListByVa ...

Implementing a location button feature on Google Maps with VueJs: A step-by-step guide

How can I implement a location button on Google Maps with VueJs? https://i.sstatic.net/qLvKV.png List of Errors: window.google.maps.event.addListener(this.map, 'center_changed', function () { secondChild.style['background-posit ...

Restoring previous configuration in Ionic2 from the resume() lifecycle method

Encountering an issue with my ionic2 application where I save the last state in local storage when the app goes to the background. Upon resuming, it checks for the value of lastState in local storage and pushes that state if a value exists. The specific er ...

What is the standard approach for indicating the lack of a specific attribute?

Is there a standardized way to specify that a specific property must definitely NOT appear on an object? I have come up with a method like this: type NoValue<T extends { value?: never, [key: string]: unknown }> = T type Foo = NoValue<{}> // Thi ...

Identify the appearance of a web component being added to the Document Object

After reading this discussion regarding a web-component I created: <my-vue-web-comp [userId]="1" id="my-component"></my-vue-web-comp> The component functions properly in Angular. How can I determine when the web component h ...

Error in TypeScript: The type 'Color' cannot be assigned to the type '"default" | "primary" | "secondary"'

Currently, I am utilizing MUI along with typescript and encountering the following issue. It seems like I may be overlooking a fundamental concept here but unfortunately cannot pinpoint it. Error: Type 'Color' is not assignable to type '&quo ...

Sorting TypeScript types by required properties first

Can anyone recommend a plugin or ESLint rule that can automatically sort types by assuming required fields come first, followed by optional fields? Here's an example before: type TExampleSorting = { title?: string; value?: number; text: string; ...

Typescript - filtering out null values from JSON object

I am facing an issue with my service method that saves a date on the server. When this method sends the date to the server, it includes fields with null values in the JSON. How can I exclude these fields with null values? public create<T>(post: any) ...

Separate the date format string into tokens

I am currently attempting to create a function that is able to transform a date format string such as %d/%m/%Y %H:%n where the variables are always denoted by a percentage sign followed by one character, into an array of tokens: ["%d", "/", "%m", "/", " ...

TypeScript does not properly validate the types of defaultProps

When working with TypeScript 3.0, I consulted the documentation at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html The recommendation is to use static defaultProps: Pick<Props, "name"> as an explicit type annotation ...

TypeScript is still throwing an error even after verifying with the hasOwnProperty

There exists a type similar to the following: export type PathType = | LivingstoneSouthernWhiteFacedOwl | ArakGroundhog | HubsCampaigns | HubsCampaignsItemID | HubsAlgos | HubsAlgosItemID | TartuGecko | HammerfestPonies | TrapaniSnowLeop ...

Determine the type of return based on the provided parameter

Can someone please assist me in understanding how to pass the typeof XXX to a method parameter and specify that the return type should be an instance of that method? Here is the method I am working with: public getComponent<T>(component: typeof Beh ...

Difficulty encountered while installing development dependency in node 0.10.x. Issue: Unable to locate a suitable version

I am currently facing an issue while attempting to run a legacy node project that requires node version "0.10.x" and npm version "1.4.x". I have set up a nodenv with node version 0.10.9 and npm version 1.2.24 This project includes a dev-dependency of "loa ...

Access to '/usr/lib/node_modules' has been denied due to error EACCES

Struggling to set up typescript using the command npm install -g typescript, I encountered the following error message: npm ERR! Error: EACCES: permission denied, access '/usr/lib/node_modules' npm ERR! at Error (native) npm ERR! ...

Creating a Typescript interface that can handle object properties of different lengths based on a specified number

https://i.sstatic.net/ItRFq.png Hello everyone, I am in need of an Input interface that adjusts its padding properties based on the number of column states. Specifically, if the column count is one, the paddings should be as follows: { ['pL-0']: ...

How to include an npm package in Laravel mix?

I've come across this question several times online, but I'm still struggling to make it work. Can someone please assist me? Currently, I am using Laravel 5.5 with Laravel Mix. Instead of manually adding required js files into specific directori ...