Having trouble in the ./src/main.ts file with an error message saying "Module not found: Can't resolve types" while trying to compile an Angular app using `ng serve`

Here is my main.ts file:

import { enableProdMode, NgModuleRef, Type, NgZone } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BootstrapPsm } from 'projects/shared/src/lib/service/bootstrap-psm';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import './polyfills';
import './assets/js/libs/pixi.min.js';
import 'foo-dts';

if (environment.production) {
  enableProdMode();
}

(Error as any).stackTraceLimit = 100;

const ngZone = new NgZone({ enableLongStackTrace: true });

platformBrowserDynamic()
  .bootstrapModule(AppModule, { ngZone })
  .then((ref: NgModuleRef<AppModule>) => {
    const bootstrap: BootstrapPsm = ref.injector.get<BootstrapPsm>(BootstrapPsm as Type<BootstrapPsm>);
    bootstrap.init();
  })
  .catch((err: Error) => console.error(err));

Additionally, I have a tsconfig.json file:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "downlevelIteration": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": false,
    "declaration": false,
    "module": "amd",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "noImplicitAny": false,
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2018", "dom"],
    "paths": {
      "foo-dts": ["./projects/shared/src/lib/types/foo-dts"]
    },
    "resolveJsonModule": true
  }
}

While trying to start the development server with ng serve, I encounter this error message:

ERROR in ./src/main.ts Module not found: Error: Can't resolve 'foo-dts' in 'C:\Users\someUser\gitProjects\user_interface\projects\baseline\src'
.

The contents of the foo-dts file are:

export {};

declare global {
  const ContentQueue: any;

  interface Date {
    format(value: string): string;
  }

  interface Window {
    ...
  }
}

Although the interfaces should be imported, they are not. Trying to fix it, I modified the types file like this:

declare module "foo-dts" {
    interface Window {
      ...
    };
}

This seemed to resolve the error, but then properties set to this interface were not exported globally, resulting in errors such as:

Property 'FooConfig' does not exist on type 'Window'
.

Even after packaging the file into an npm package and installing it, and importing it using import '@types/foo-dts';, the same 'module not found' error persisted.

I am struggling to find the correct solution to this issue.

Answer №1

Discovered the solution by exploring different related topics and experimenting with various methods.

In the end, I had to bundle my typings file to make it accessible as a separate typings module within node_modules/@types. Then, I included

"typeRoots": ["node_modules/@types"],
in the root tsconfig.json file and added the name of the typings package to the
"types": ["foo-dts"]
arrays in different tsconfig.*.json configurations across subdirectories.

If you already have a

"types": ["some_types", "node", "jasmine"]
array in your configuration file, simply append your custom types' name enclosed in double quotes like so:
"types": ["some_types", "node", "jasmine", "some_custom_types"]
.

I only added them where these types were necessary. Therefore, if a specific subdirectory didn't require these types for libraries/components/tests to function, they weren't included.

The "types" array must be located within the "compilerOptions" object of the tsconfig.*.json file.

To achieve this, I created a directory called foo-dts inside the root folder of the app at

C:\Users\someUser\gitProjects\user_interface
.

I placed two files there.

The first was index.d.ts:

declare global {
  interface Window {
    // list of properties here...
  }
}
export {};

The second file was package.json:

{
  "name": "@types/foo-dts",
  "version": "1.0.0",
  "description": "Declaration files for legacy Foos",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "me",
  "license": "Super-duper license"
}

Next, I added

"@types/foo-dts": "file:./foo-dts"
to the "devDependencies": {} section of the root package.json configuration.

Afterwards, I ran npm i to install dependencies and that's it!

My IntelliJ IDEA Ultimate flawlessly recognized the types while serving the local development server with ng serve and running unit tests with ng test --watch=false.

It's unfortunate that such a straightforward solution is not explicitly documented and easily accessible.

I had to navigate through Angular and TypeScript documentation, as well as various similar issues on StackOverflow and blogs, before finally grasping how to implement the fix.

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

Save information on the server and organize it into an array for use in local operations

Currently, I am working on the ShoppingApp using Angular for the front-end and Firebase for the backend. I have defined a model for the category as follows: import { ProductModel } from "./product.model"; export class CategoryModel { public id: number; ...

I am experiencing issues with my Jest unit test case for Material UI's multi select component failing

I've been working on writing a unit test case for the material UI multi select component. The code for the parent component is as follows: import {myData} from '../constant'; export const Parent = () => { const onChangeStatus= (sel ...

When utilizing gapi (typescript) to send emails, the Sent box may contain incorrectly encoded email messages

When I send emails using gapi, the receiver receives them correctly. However, when I check my "Sent" box, the emails appear as Chinese gibberish characters like in this image. This issue only occurs when using non-gmail applications. If I view the Sent bo ...

Locate the python3 modules

Having some trouble getting my sample database connection to work with my mariadb database. python3 sample.py Traceback (most recent call last): File "sample.py", line 3, in <module> import mysql.connector as mariadb ModuleNotFoundError: ...

Managing errors within a Resolve service is crucial

Imagine a scenario where you have a DataComponent, which showcases an array of Data in an HTML table. // data.ts export class Data { ... } // data.component.ts @Component(...) export class DataComponent { ... } To follow good programming practices, yo ...

Incorporating JointJS into your project

After following the guide on How to integrate JointJS with an Angular CLI application, I encountered a problem when starting the project: Module not found: Error: Can't resolve './node_modules/jointjs/dist/joint.js' I attempted to change t ...

Having trouble accessing the undefined property 'ngOnInit' and 'getData' in Angular while conducting unit tests with Jasmine

Looking to write a unit test for my component file that subscribes to a method in the service layer Homecomponent.ts import { Data } from './../model/data.model'; import { DataService } from './../services/data.service'; import { Comp ...

Issue with module import in Next.js: "<module name>__WEBPACK_IMPORTED_MODULE_1___default(...).<function name>" Are We Making a Mistake?

I have a basic Next.js project with TypeScript that I have enhanced by adding Jimp. I am utilizing the experimental app directory in my configuration. This is how my next.config.js file looks: /** @type {import('next').NextConfig} */ const nextC ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

The properties of cloned objects in ThreeJS are unable to be defined

While working in ThreeJS using TypeScript, I encountered an issue when attempting to clone a custom object that extends Object3D. The problem arises when the field, which is required for creating a new object, becomes undefined during the cloning process. ...

webpack is having trouble compiling TypeScript with React components

I've been working on setting up a TypeScript React project with webpack. I followed the TypeScript Tutorial, but I keep running into an error message that says `module parse failed: ... you may need an appropriate loader` Interestingly, I can success ...

What is the best way to establish a restriction on the number of items obtained from an RSS

I am receiving a feed from this specific link. My goal is to only retrieve the initial five items from the feed, but currently I am getting all of the items. Is there a way for me to specifically request only the first five items? Do I need to include an ...

Error message: WebStorm shows that the argument type {providedIn: "root"} cannot be assigned to the parameter type {providedIn: Type<any> | "root" | null} and InjectableProvider

Transitioning my app from Angular v5 to v6 has presented me with a TypeScript error when trying to define providedIn in my providers. The argument type {providedIn: "root"} cannot be assigned to the parameter type {providedIn: Type | "root" | null} & ...

The progress bar is only displayed during the initial consecutive file uploads in Angular 6

Within my Angular application, I have implemented a dedicated form for uploading profile pictures. The process involves triggering a confirmation modal upon uploading a new image, followed by the display of a progress bar on the page. This progress bar ind ...

A guide to accessing Firebase push notification content and triggering a method in Ionic 2

Can Ionic 2 allow access to push notification content and trigger a set of actions when notifications arrive or events are fired? ...

Creating Open API Spec from Model/Controller Metadata in Loopback4

Is there a method in Loopback4 that allows for the creation of an Open Api Spec using decorated models and controllers? If not, is there a means to retrieve controllers and models metadata during runtime? ...

Develop an encoding feature utilizing mustache templates

Exploring the world of mustache for the first time, I haven't been able to find the answer through my basic searching. I am attempting to create a template in Typescript for encoding an unknown number of fields. The structure will be something like th ...

Throw TypeError: The `pipe` property of `ngrx/store` is undefined during testing

Here is the code snippet from my TypeScript file: this.store.pipe(select(subscribe.getRegCategories)).pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => { if (data && data.length) { this.allRegCategories = data; ...

What is the most effective method to inform TypeScript that every element in an array is present in a Map?

Consider a scenario where you are creating a Map from an array of objects with unique ids as keys, and then accessing the map from another array that shares the same ids: const arr1 = [ {id: 'a', firstName: 'Mike'}, {id: 'b&apo ...

What are some ways to prevent unnecessary HTML re-rendering when using this.sanitizer.bypassSecurityTrustHtml(value)?

What is the best way to prevent constant HTML re-rendering when utilizing (this.sanitizer.bypassSecurityTrustHtml(value)) in Angular versions 5 and above? ...