Thursday, 20 May 2021

Typescript & TypeORM: Cannot use import statement outside a module

I've set up a Typescript project with TypeORM and I am facing some issues with the compilation.

My package structure is like this:

root
├── db
│   ├── migrations
│   │   ├── a_migration.ts
│   ├── connection
│   │   ├── config.ts <- ormconfig
│   │   ├── encrypt.ts
│   │   ├── index.ts <- creates the connection
├── src
│   ├── card
│   │   ├── entity.ts
├── package.json
├── tsconfig.json

My config.ts is:


export = {
  type: 'postgres',
  host: POSTGRES_HOST,
  port: POSTGRES_PORT,
  username: POSTGRES_USER,
  password: POSTGRES_PASS,
  database: POSTGRES_DB,
  synchronize: true,
  logging: false,
  entities: ['**src/**/*entity.{ts,js}'],
  migrations: ['**/migrations/*.{ts,js}'],
  cli: {
    entitiesDir: 'src/entity',
    migrationsDir: 'db/migrations',
  },
  namingStrategy: new SnakeNamingStrategy(),
};

tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "es6",
    "module": "CommonJS",
    "allowJs": false,
    "esModuleInterop": true,
    "noImplicitAny": true,
    "resolveJsonModule": true,
    "outDir": "./build",
    "strict": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "include": ["./src/*", "./db/*"],
  "exclude": ["./**/__tests__/*", "./**/__functionaltests__/*"]
}

I tried replacing the ** prefix in entities & migrations with a path.join + __dirname but then typeorm could not detect the migration files and the entities. I understand this has something to do with the path resolving where the code ends up under the build folder but I am not sure how I can tackle this.

If I live it like this the CLI works for the uncompiled code (ts) executing the app with something like nodemon but not for the compiled (js) one.

The error I am getting from the compiled js is the: SyntaxError: Cannot use import statement outside a module

Any help is appreciated, thanks a lot!



from Typescript & TypeORM: Cannot use import statement outside a module

No comments:

Post a Comment