TypeORM Entity in NESTJS - Cannot use import statement outside a module
In the TypeORM documentation, i found a specific section for Typescript.
This section says:
Install ts-node globally:
npm install -g ts-node
Add typeorm command under scripts section in package.json
"scripts" { ... "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js" }
Then you may run the command like this:
npm run typeorm migration:run
If you need to pass parameter with dash to npm script, you will need to add them after --. For example, if you need to generate, the command is like this:
npm run typeorm migration:generate -- -n migrationNameHere
This works with my file config:
{
"type": "postgres",
"host": "yourhost",
"port": 5423,
"username": "username",
"password": "password",
"database": "your_db",
"synchronize": true,
"entities": [
"src/modules/**/*.entity.{ts,js}"
],
"migrations": [
"src/migrations/**/*.{ts,js}"
],
"cli": {
"entitiesDir": "src/modules",
"migrationsDir": "src/migrations"
}
}
Then you can run the generate command.
I changed in tsconfig.json file next:
"module": "es6"
To:
"module": "commonjs",
It helps me
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.
EDIT 1/10/2020
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.
As Jay McDoniel explained in his answer, the problem seems to be the pattern matching of entity files in ormconfig.json
file: Probably a typescript file (module) is imported from a javascript file (presumably a previously transpiled typescript file).
It should be sufficient to remove an existing ts
glob pattern in the ormconfig.json
, so that TypeORM will only load javascript files. The path to the entity files should be relative to the working directory where node is executed.
"entities" : [
"dist/entity/**/*.js"
],
"migrations" : [
"dist/migration/**/*.js"
],
"subscribers": [
"dist/subscriber/**/*.js"
],