'Syntax Error on TypeScript file when using TypeORM with JavaScript file

I'm getting a SyntaxError when running a TypeScript-compiled JS file [via TypeORM].

I have the following files:

// ./src/entity/Bird.ts

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

@Entity()
export class Bird {
    @PrimaryGeneratedColumn()
    id: number;
    
    @Column()
    kingdom: string;
    
    @Column({length: 300})
    phylum: string;
    
    @Column()
    class: String;
    
    @Column({type: 'simple-array'})
    colors: string[];
    
    @Column({default: false})
    isActive: boolean;
    
    @Column({type: 'bigint', width: 100, default: Date.now()})
    timestamp_u: number;
}
// ./init.ts

import 'reflect-metadata';
import { createConnection } from 'typeorm';

async function start() {
    // initialize database
    let connection = await createConnection();

    // close connection
    await connection.close();
}

start().catch(console.error);
// ./ormconfig.json
{
   "type": "mysql",
   "host": "localhost",
   "port": 3306,
   "username": "root",
   "password": "my~password",
   "database": "sandbox",
   "synchronize": true,
   "logging": false,
   "entities": [
      "dist/src/entity/**/*.js",
      "src/entity/**/*.ts"
   ]
}
// ./tsconfig.json
{
   "compilerOptions": {
      "lib": [
         "es5",
         "es6"
      ],
      "target": "es6",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "./dist",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true
   },
   "exclude": ["node_modules", "dist", "out"]
}

In package.json, type is set to commonjs [for ts-node to work properly];

I'm compiling TypeScript to JavaScript:

npx tsc

Then I'm running the JavaScript via Node:

node ./dist/init.js

When I do this, I get the following error:

Bird.ts:1
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
^^^^^^

SyntaxError: Cannot use import statement outside a module

The problem goes away when I change my ormconfig.json to this:

...
"entities": [
      "dist/src/entity/**/*.js"
   ]
...

Note: I've removed the entities directory for TypeScript files.

However, I need to re-include that directory when I use ts-node.

My questions are:

  1. Why is Node [via TypeORM I surmise] giving me an error regarding a .ts file when I'm running a .js file?
  2. Is there some configuration setting I can make to have both directories in place and not get the error?


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source