Error: TypeORM entity import token is not recognized

Currently, I am facing a peculiar error while transpiling my TypeScript code to JavaScript using TypeORM. The error message that pops up is as follows:

(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, ManyToOne, OneToMany, TreeChildren, TreeParent, JoinColumn, Column, Tree, TreeLevelColumn } from "typeorm";
                                                              ^^^^^^

SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Function.PlatformTools.load (C:\Users\*redacted*\Workspace\experimental\*redacted*\node_modules\typeorm\platform\PlatformTools.js:126:28)

This issue arises when I run the following command in my tsconfig.json:

{
    "compilerOptions": {
        "lib": [
           "es5",
           "es6"
        ],
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "outDir": "./build",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "sourceMap": true
     },
    "exclude": [
        "client"
    ]
}

And here's what my package.json looks like:

{
   "name": "*redacted*",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "dev": "nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec ts-node src/index.ts",
      "start": "tsc && node ./build/index.js",
      "migrate": "ts-node ./node_modules/typeorm/cli.js migration:generate"
   },
   "author": "*redacted*",
   "license": "ISC",
   "dependencies": {
   ...
   },
   "devDependencies": {
   ...
   }
}

The source file where the error originates from contains the following code snippet:

import { Entity, PrimaryGeneratedColumn, ManyToOne, OneToMany, TreeChildren, TreeParent, JoinColumn, Column, Tree, TreeLevelColumn } from "typeorm";
import { User } from "./User";
import { Debate } from "./Debate";

// More TypeScript code goes here...

I have attempted several troubleshooting methods which include updating my Node.js version, adjusting the compiler options in tsconfig.json, and modifying the import statements within my entity files without much success.

If you have any insights or suggestions on how to resolve this dilemma, your input would be highly appreciated.

Answer №1

Okay, I'll admit it, sometimes I can be a bit clueless.

So, here's the deal with ormconfig.json: it directs your entities to your TypeScript files in the /src folder. When you compile your project, make sure it knows where to find your entities. It seemed strange to me too that it was trying to reference a TS file post build.

ormconfig.json

{
   "type": "postgres",
   "host": "**********************",
   "port": 5432,
   "username": "**************",
   "password": "*************",
   "database": "*************",
   "synchronize": true,
   "logging": false,
   "entities": [
      // made some changes here

      "dist/entity/*.js"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],
   "cli": {
      "entitiesDir": "src/entity",
      "migrationsDir": "src/migration",
      "subscribersDir": "src/subscriber"
   }
}

Answer №2

Utilizing ts-node for running typeorm provides the advantage of executing ts files without the need to compile and run separate js files.

As mentioned in this particular github comment, the process involves:

1.- Installing ts-node and typescript globally:


  $ npm install -g ts-node typescript
  

2.- Running the typeorm command with ts-node:


  $ ts-node ./node_modules/.bin/typeorm migrations:generate -n
  

In case you encounter issues on Windows, referring directly to cli.js as per this specific comment is recommended:


  ts-node node_modules\typeorm\cli.js
  

Answer №3

I also experienced a similar issue, where the problem arose from mistakenly importing 'BaseEntity' from 'typeorm/browser' instead of 'typeorm'.

It turns out that the first one is a JavaScript file, while the second is a TypeScript file.

Answer №4

I once encountered a similar problem and realized it was due to my own oversight. Instead of naming the file with the .ts extension, I mistakenly used .js.

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

Utilize the ng2-select component to incorporate multiple instances within a single webpage

Can someone help me figure out how to use two ng2-select components in my modal? I've checked out the documentation, but it doesn't provide any information on using more than one select. I'm not sure how to capture the selected values of ea ...

Error: The 'Window' object is not defined. The use of Client in NextJS13 is not

I've been attempting to integrate NextJS 13 with react-leaflet, but I keep encountering the error "window is not defined" when running my component. I attempted using the "use client" declaration at the beginning of the file and adding a check for "ty ...

Module for importing text without verifying types using wildcards

Here is a unique module definition using the wildcard character: declare module 'custom!*' { const data: string; export default data; } Check out how it's imported: import * as myData from 'custom!./myCustomData.txt'; B ...

The type of link component that is passed in as the 'component' prop

I have created a custom Button Function Component in TypeScript using Material-UI as the base. After styling and adding features, I exported it as my own Button. Now, when I try to use this Button component in conjunction with the Link component from react ...

Testing Angular: How to Unit-test HttpErrorResponse with custom headers using HttpClientTestingModule

In the code snippet below, I am attempting to find a custom header on error: login(credentials: Credentials): Observable<any> { return this.http.post(loginUrl, credentials) .pipe( catchError((httpErrorResponse: HttpErrorRespo ...

Error: ngModel does not reflect dynamic changes in value

After calling a Spring service, I am receiving JSON data which is stored in the "etapaData" variable. 0: id: 266 aplicacao: {id: 192, nome: "Sistema de Cadastro", checked: false} erro: {id: 220, nome: "Falta de orçamento", checked: false} perfil: {id: 8, ...

Issues may arise in TypeScript when you are working with an array of objects along with other properties within a type

I am encountering an issue with an object structure similar to the one below: let Obj = { ['0'] : { mode: 'x' }, getMode: () => 'x' } The problem arises when I attempt to create a type definition as shown here: type Obj = ...

Having trouble fixing TypeScript bugs in Visual Studio Code

I am encountering a similar issue as discussed in this solution: Unable to debug Typescript in VSCode Regrettably, the suggested solution does not seem to resolve my problem. Any assistance would be greatly appreciated. My directory structure looks like ...

Steps to globally modify the font in Ionic

In my Ionic app running version 3.9.2, I am attempting to customize the default font to a specific custom one. After researching, I discovered that I need to set the font face in the app.scss file located within the app folder. Here is the code snippet I ...

Error encountered during unit testing: The function _reactRouterDom.useHistory.mockReturnValue is not a valid function

I'm having trouble writing unit tests for a React component implemented in TypeScript. I encountered an error when trying to mock some hook functions. Here is my current unit test implementation: import React from 'react'; import { useHisto ...

Using TypeScript and NestJs: Spread types can only be generated from object types

I'm encountering an issue while trying to pass two parameters using the spread operator from the book.controller to the book.service.ts service. The error message I'm receiving is: Spread types may only be created from object types It's w ...

Can you explain what comes after the equal sign in a TypeScript object?

While browsing through this response on stackoverflow The author answered: // How I usually initialize var foo:IFoo = <any>{}; I attempted to research it online, but unfortunately, I couldn't find any information about it. Could someone expl ...

While attempting to send a GET Request in Angular, access to XMLHttpRequest has been denied due to CORS policy restrictions

I am attempting to establish a GET method for my PHP API. Here is the code snippet I am using: export class PerfilComponent { perfil: any; constructor(private http: HttpClient) { } ngOnInit() { const token:string | null = localStorage.getItem(&ap ...

How to dynamically modify ion-list elements with Ionic on button click

Imagine having 3 different lists: List 1: bus, plane List 2: [related to bus] slow, can't fly List 3: [related to plane] fast, can fly In my Ionic Angular project, I have successfully implemented the first ion-list. How can I dynamically change th ...

Creating a TypeScript library with Webpack without bundling may seem like a daunting task, but

Currently, I am developing a React component package using Typescript and NPM. During my research, I discovered that generating individual .js and .d.ts files is more beneficial than bundling them into one bundle.js file. However, I am facing difficulty in ...

What causes the difference in behavior between packed and non-packed generics?

When attempting to exclude properties outside of generics, it functions properly but results in a breakdown within the generic context. The issue lies in the fact that Omit<Thing, 'key1' | 'key2'> transforms into Omit<Thing, &a ...

In Vue3, when using the `script setup` with the `withDefaults` option for a nested object, its attributes are marked as required. How can this issue

I have defined a props object with certain attributes: interface Props { formList: BaseSearchFormListItemType[], inline?: boolean searchBtn?: { show?: boolean text?: string type?: string size?: string } } const props = withDefaults( ...

Extending a generic typed class in Typescript allows for the creation of

I am interested in extending the following class: import 'reflect-metadata'; import { IRepository, IFireOrmQueryLine, IOrderByParams, IEntity } from './types'; import { AbstractFirestoreRepository } from './AbstractFirestoreReposit ...

I'm looking for the Type Definitions Files (*.d.ts) for the Amazon Cognito Identity SDK. Does anyone know where I can find them and how

Where can I locate Type Definitions Files (*.d.ts) for the Amazon Cognito Identity SDK and how can I use them? I am utilizing TypeScript for Angular2 and I would like to have the code assistant readily available when implementing "AWS Cognito." While I al ...

Removing empty options from a select dropdown in Angular 9

In the process of working with Angular 9, I am currently in the process of constructing a dropdown menu that contains various options. However, I have encountered an issue where there is a blank option displayed when the page initially loads. How can I eli ...