Typeorm - Cannot use import statement outside a module

In a NestJS application, I created a custom entity along with its corresponding controller and service. When I started the application, I encountered the following error:

TypeORM Entity in NESTJS - Cannot use import statement outside a module

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:984:16)
    at Module._compile (internal/modules/cjs/loader.js:1032:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:933:32)
    at Function.Module._load (internal/modules/cjs/loader.js:774:14)
    at Module.require (internal/modules/cjs/loader.js:957:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at tryToRequire (A:\work\nestapp\src\util\ImportUtils.ts:21:17)
    at importOrRequireFile (A:\work\nestapp\src\util\ImportUtils.ts:35:25)
    at A:\work\nestapp\src\util\DirectoryExportedClassesLoader.ts:57:45

What does this error mean?

NestJS doesn’t load TypeScript or JavaScript files in a TypeScript context. The TypeORMModule expects ORM configuration, where the entities attribute expects a regular expression pattern to pick entities in the src module that start with .ts or .js files. According to the TypeORM documentation, entities accepts entity classes, entity schema classes, and directory paths to load from. Directories support glob patterns.

The error occurs due to an invalid configuration of entities or migrations in the ORM configuration file. It should always reference files in the TypeScript context.

Here are the steps to resolve this:

First, check tsconfig.json to ensure the module entry contains commonjs instead of es6:

{
  "compilerOptions": {
    "module": "commonjs"
  }
}

Next, check the regular expression pattern for entities or migrations in the ORM configuration file.

For example, if entities is configured like this

import { DataSourceOptions } from "typeorm";

const config: DataSourceOptions = {
  type: "mysql",
  host: "localhost",
  port: 3306,
  username: "root",
  password: "",
  database: "test",
  entities: ["**/*.entity{.ts,.js}"],
  synchronize: true,
};
export default config;

For example, entitites

   "entities": [
        "**/*.entity{.ts,.js}"
    ],

replace with

"entities": [
        "dist/**/*.entity{.ts,.js}"
    ],

Alternatively, if the above doesn’t work, change it to:

entities: [join(__dirname, "**", "*.entity.{ts,js}")];

Make sure to verify and adjust these entries accordingly.