Having trouble executing NestJS in production mode due to missing module

After implementing a generic class as shown below, an issue seems to have arisen:

    import { Logger } from '@nestjs/common';
    import { PaginationOptionsInterface, Pagination } from './paginate';
    import { Repository } from 'typeorm';

    export class EntityService<T> {
      private repository: Repository<T>;
      constructor(repository) {
        this.repository = repository;
      }

      async getEntityWithPagination(
        options: PaginationOptionsInterface,
      ): Promise<Pagination<T>> {
        const [results, total] = await this.repository.findAndCount({
          take: options.limit,
          skip: (options.page - 1) * options.limit,
        });
        return new Pagination<T>({ results, total });
      }
    }

I am also utilizing this class with other entity services, like so:

    @Injectable()
    export class CarService extends EntityService<CarEntity> {
      constructor(
        @InjectRepository(CarEntity)
        private carRepository: Repository<CarEntity>,
      ) {
        super(carRepository);
      }

The code functions correctly when running npm run start:dev, but it throws the following error when attempting to run in production using npm run start:prod:

        internal/modules/cjs/loader.js:582
            throw err;
            ^

        Error: Cannot find module 'src/shared/entity.service'
            at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
            at Function.Module._load (internal/modules/cjs/loader.js:506:25)
            at Module.require (internal/modules/cjs/loader.js:636:17)
            at require (internal/modules/cjs/helpers.js:20:18)
            at Object.<anonymous> (/home/tejas/Code/web/project/dist/car/car.service.js:27:26)
            at Module._compile (internal/modules/cjs/loader.js:688:30)
            at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
            at Module.load (internal/modules/cjs/loader.js:598:32)
            at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
            at Function.Module._load (internal/modules/cjs/loader.js:529:3)
        npm ERR! code ELIFECYCLE
        npm ERR! errno 1
        npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e595978a8f808691a5d5cbd5cbd5">[email protected]</a> start:prod: `node dist/main.js`
        npm ERR! Exit status 1

Attempts to resolve the issue by deleting the dist folder and updating packages were unsuccessful. The package.json configuration is provided below. Help with debugging would be greatly appreciated.

        dependencies": {
            "@nestjs/common": "^5.5.0",
            "@nestjs/core": "^5.5.0",
            "@nestjs/jwt": "^0.2.1",
            "@nestjs/passport": "^5.1.0",
            "@nestjs/typeorm": "^5.2.2",
            "bcryptjs": "^2.4.3",
            "glob": "^7.1.3",
            "passport": "^0.4.0",
            "passport-http-bearer": "^1.0.1",
            "passport-jwt": "^4.0.0",
            "pg": "^7.7.1",
            "reflect-metadata": "^0.1.12",
            "rimraf": "^2.6.2",
            "rxjs": "^6.2.2",
            "typeorm": "^0.2.9",
            "typescript": "^3.2.2"
        },
        "devDependencies": {
            "@nestjs/testing": "^5.5.0",
            "@types/express": "^4.16.0",
            "@types/jest": "^23.3.1",
            "@types/node": "^10.12.18",
            "@types/supertest": "^2.0.7",
            "jest": "^23.5.0",
            "nodemon": "^1.18.9",
            "prettier": "^1.14.2",
            "supertest": "^3.1.0",
            "ts-jest": "^23.1.3",
            "ts-loader": "^4.4.2",
            "ts-node": "^7.0.1",
            "tsconfig-paths": "^3.5.0",
            "tslint": "5.11.0",
            "webpack": "^4.28.2",
            "webpack-cli": "^3.1.2",
            "webpack-node-externals": "^1.7.2"
        },

Answer №1

The root cause has been identified - an absolute path was used while importing the class.

import { EntityService } from '../shared/service-common'; //this is the correct way

import { EntityService } from 'src/shared/service-common'; // this is the incorrect auto import

To address the auto import issue, I have made a configuration change in VS Code

"typescript.preferences.importModuleSpecifier": "relative"

Answer №2

To start fresh, remove the dist directory and then execute: npm run start:dev

Answer №3

Make sure that the script you are using is directed to main.js within the dist folder.

"start:prod": "node dist/src/main"

Answer №4

A similar issue I encountered was related to a misalignment in file naming conventions, where the reference had capitalization that did not match the actual filename:

import { AnotherClass } from './another-class'; 

despite the file being named AnotherClass.ts

Correcting the import statement helped rectify the issue.

Answer №5

It's important to note that storing js/ts files (including imported modules) outside the src folder could lead to complications when executing start:prod

For example, I had a seed.ts file for populating my database using Prisma ORM. Once I relocated it into the src folder, the problem was resolved.

Answer №6

The Fix

To resolve this issue, simply delete the noEmit property from the compilerOptions section in the tsconfig.json file.

Answer №7

Occasionally, the issue may stem from preexisting code located outside of the SRC directory (such as Typeform migrations) that results in the compilation within DIST navigating through additional folder levels (e.g., dist/migrations, dist/src), preventing the main file from being in its intended location.

Answer №8

To fix the issue, I successfully resolved it by removing the automatically generated files and reconstructing them, specifically the dist folder.

Answer №9

In case your issue is not related to relative directory problems, you can attempt resolving it by deleting the dist folder and then running npm run start:prod once more. Additionally, if there is a file named tsconfig.build.tsbuildinfo, make sure to delete that as well.

Answer №10

It slipped my mind to include these essential packages for mikro-orm. Once I installed them, my problem was resolved:

yarn add @mikro-orm/core @mikro-orm/nestjs

Answer №11

My simple solution was to avoid using spaces in the folder names. For example, instead of writing "codes projects," I had to write it as "codes_projects" for it to be recognized properly. It may seem obvious, but sometimes the easiest solutions are overlooked.

Answer №12

This information may not apply to everyone, but in my particular situation, the issue was triggered by an instanceOf...

We had a function that took two different types of parameters

fetchElement(svc: TypeA | TypeB) {
  svc instanceof TypeA
}

I'm not sure why, but the problem was resolved once we removed this portion.

Answer №13

The issue is triggered by the use of capitalized file names.

Key-store.entity.ts -> key-store.entity.ts

To resolve this, ensure all filenames are in lowercase.

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

Creating a nested observable in Angular2: A step-by-step guide

Currently, I am exploring a new approach in my Angular2 service that involves using observables. The data source for this service will initially be local storage and later updated when an HTTP call to a database returns. To achieve this dynamic updating of ...

What could be the reason that the _.sample function in lodash is producing a return type of number

Sample Scenario 1 const myNumber = _.sample([1, 2, 3]); // Anticipated data type: number // Real data type: number Sample Scenario 2 const arr = [1, 2, 3] const myNumber = _.sample(arr); // Anticipated data type: number // Real data type: number | undefin ...

Difficulty in retrieving template variable within mat-sidenav-content

I am attempting to change a css class by targeting a div with a template variable within mat-sidenav-content. I have tried using both @ViewChild and @ContentChild but neither of them is able to retrieve the reference of the specified div at runtime. Below ...

Is the naming convention for parameterized types (T, U, V, W) in Generics adhered to by Typescript?

Is TypeScript following the same naming convention for parameterized types as other languages like C++ and Java, using T,U,V,W, or is there a mixed usage of conventions? In the TS 2.8 release notes, we see examples like: type ReturnType<T> = T exten ...

Step-by-step guide on invoking an asynchronous method in canActivate for Ionic and Angular

My objective is to acquire a token for authenticating users. I am utilizing the import { Storage } from '@ionic/storage-angular'; to store the data, but I am encountering an issue where the Storage methods only function in asynchronous mode. Her ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

What is the best way to combine two responses and then convert them into a promise?

When making two calls, the firstCallData prints data fine. However, when I use + to merge the responses, it returns me the following Response. What is a better approach to achieve this task? main.ts let data = await this.processResponse(__data.Detail ...

The issue arises when Jest ceases to function properly once the "type": "module" is configured in the tsconfig.json file

I have encountered an issue while using jest for unit testing in typescript. When I set "type": "module" in the tsconfig.json file, my app runs perfectly fine but jest stops working and displays a "ReferenceError: require is not defined". const { pathsToMo ...

Utilizing sourcemaps in ionic for seamless linking

I've encountered an issue with source maps or a similar feature. After inserting console.log(...) in my code, the message appears in the console but links to the compiled JavaScript file instead of the original TypeScript file. Have I overlooked som ...

Replacing URLs in Typescript using Ionic 3 and Angular

Currently facing some difficulties getting this simple task to work... Here is the URL format I am dealing with: https://website.com/image{width}x{height}.jpg My objective is to replace the {width} and {height} placeholders. I attempted using this func ...

Typescript fetch implementation

I've been researching how to create a TypeScript wrapper for type-safe fetch calls, and I came across a helpful forum thread from 2016. However, despite attempting the suggestions provided in that thread, I am still encountering issues with my code. ...

Differences between React Typescript: @types/react-router-dom and react-router-dom

Hello there! This is my first time working with Typescript in a React project, and I'm feeling a bit confused about the @types npm packages. Can someone explain the difference between @types/react-router-dom and react-router-dom, as well as suggest wh ...

Ways to incorporate environment variable in import statement?

In my Angular v5 project, I have a situation where I need to adjust the import path based on the environment. For example, I have an OwnedSetContractABI file located in different folders for each environment - dev and production. In dev environment, the ...

Angular's OnChanges event is triggering for an Input variable, however the variable remains unchanged

I've encountered a new issue that I'm hoping someone can help me with. I'm working on a simple parent-child component relationship where an Input variable is passed into a ChildComponent. The ChildComponent in question is a bootstrap modal, ...

Can I exclusively utilize named exports in a NextJS project?

Heads up: This is not a repeat of the issue raised on The default export is not a React Component in page: "/" NextJS I'm specifically seeking help with named exports! I am aware that I could switch to using default exports. In my NextJS ap ...

Is there an alternative method to incorporate the 'environment.ts' file into a JSON file?

In my Angular application, I need to import assets based on the env configuration. I am attempting to extract the patch information from environment.ts and save it into my assets as a json file. However, I am unsure of the proper method to accomplish this. ...

Encountered a runtime error in NgRx 7.4.0: "Uncaught TypeError: ctor is not a

I'm facing difficulties trying to figure out why I can't register my effects with NgRx version 7.4.0. Despite simplifying my effects class in search of a solution, I keep encountering the following error: main.79a79285b0ad5f8b4e8a.js:33529 Uncau ...

What is the best way to "connect" an interface in TypeScript?

I'm working on creating a child interface that mirrors the structure of a base interface. Any tips on how to achieve this? interface BaseInterface { api: { [key: string]: string }; ui: { [key: string]: string }; } interface ChildInterface { / ...

Creating an overloaded callable interface using TypeScript

The thread on implementing a callable interface provides some helpful information, but it doesn't fully address my specific query. interface lol { (a: number): (b: number) => string // (a: string): (b: string) => string // overloaded wi ...

Error in React.tsx Material UI Tab - Avoid using curly braces "{}" as a data type

Currently, I am working on a React TS project and facing an issue while trying to import the Material UI tabs for scrollable functionality. The specific Tabs/Scrollable Tabs example from Material-UI documentation is what I'm referring to: https://mate ...