Started new project with \'nest new\' command. Works fine until I add entity file to it.
Got following error:
import { Entity, Column, Primary
I was using Node.js with Typescript and TypeORM when I faced this issue. Configuring in ormconfig.json file worked for me.
entities: ['dist/**/*.entity.js']
My full code of ormconfig.json file:
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "xxxxxxxx",
"password": "xxxxxxxx",
"database": "typescript_orm",
"synchronize": true,
"logging": false,
"migrationTableName": "migrations",
"entities": [
"dist/**/*.entity.js"
],
"migrations": [
"src/migration/**/*.{ts, js}"
],
"suscribers": [
"src/suscriber/**/*.{ts, js}"
],
"cli": {
"entitiesDir": "src/model",
"migrationDir": "src/migration",
"suscribersDir": "src/suscriber"
}
}
Configuration to support migrations:
// FILE: src/config/ormconfig.ts
const connectionOptions: ConnectionOptions = {
// Other configs here
// My ormconfig isn't in root folder
entities: [`${__dirname}/../**/*.entity.{ts,js}`],
synchronize: false,
dropSchema: false,
migrationsRun: false,
migrations: [getMigrationDirectory()],
cli: {
migrationsDir: 'src/migrations',
}
}
function getMigrationDirectory() {
const directory = process.env.NODE_ENV === 'migration' ? 'src' : `${__dirname}`;
return `${directory}/migrations/**/*{.ts,.js}`;
}
export = connectionOptions;
// FILE package.json
{
// Other configs here
"scripts": {
"typeorm": "NODE_ENV=migration ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/config/database.ts",
"typeorm:migrate": "npm run typeorm migration:generate -- -n",
"typeorm:run": "npm run typeorm migration:run",
"typeorm:revert": "npm run typeorm migration:revert"
}
}
My assumption is that you have a TypeormModule
configuration with an entities
property that looks like this:
entities: ['src/**/*.entity.{ts,js}']
or like
entities: ['../**/*.entity.{ts,js}']
The error you are getting is because you are attempting to import a ts
file in a js
context. So long as you aren't using webpack you can use this instead so that you get the correct files
entities: [join(__dirname, '**', '*.entity.{ts,js}`)]
where join
is imported from the path
module. Now __dirname
will resolve to src
or dist
and then find the expected ts
or js
file respectively. let me know if there is still an issue going on.
The above assumes the configuration is done is a javascript compatible file (.js
or in the TypeormModule.forRoot()
passed parameters). If you are using an ormconfig.json
instead, you should use
entities: ["dist/**/*.entity.js"]
so that you are using the compiled js files and have no chance to use the ts files in your code.
I changed in tsconfig.json file next:
"module": "es6"
To:
"module": "commonjs",
It helps me