{

Typeorm - Cannot use import statement outside a module


IN NestJS application, Created an Custom Entity and corresponding Controller, Service and started an application, got an below error during startup.

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 means?

Nestjs does not load the files ts or js files in typescript context. TypeormModule expects orm configuration, which entities attributes expects the regular expression patter that picks entities in src module that starts with ts or js files. As per typeorm documentation, entities accepts entities - Entities, or Entity Schemas, to be loaded and used for this data source. Accepts both entity classes, entity schema classes, and directories paths to load from. Directories support glob patterns.

entities contains array of typescript files or patterns. Following are the steps to required.

First step, Check tsconfig.json for module entrie contains commonjs instead of es6

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

Next, step check an regular expression pattern for entities or migrations in ormconfiguration file

The error throws during invalid configuration of entities or migrations in ormconfiguration file.

It should always pointed to files in the typescript context.

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;

Please check this two entries values

For example, entitites

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

replace with

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

Another way, if it does not works above, Please change the as given below

entities: [join(__dirname, '**', '*.entity.{ts,js}')]
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.