New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unable to use file path for loading entities and Entity Load Order #7516
Comments
I transpile my ts to a Here's my config for entities which works fine: createConnection({
...,
entities: ['build/db/entities/*.js']
}) |
Yes, in my post, I transpile to the bin directory, the "this._entity_path" variable includes bin in the path. i.e. bin/models/entities. This can be see in the error messages |
So this is happening because you are trying to output ES modules from the typescript compilation step, and down inside of I'm not sure if there's an easy fix for TypeORM here. If they switch to Unless it could do some introspection and check if require exists, and if it does, use the require function, else use the await import function. |
Same problem here, with an hybrid codebase (js/ts), this problem seems inevitable when updating ts-node to versions 10.x, I don't have any problem with ts-node 9.1.1 though. |
This is pretty much problematic for any app which is on node 14 and higher and for which the runtime is fully modular. EDIT: by the way |
I meet the same problem,and I regist classes by this way. import path from 'path';
import { fileURLToPath } from 'url';
import { createConnection } from 'typeorm';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const js_files = fs.readdirSync(path.resolve(__dirname, './entities')).filter((f) => {
return f.endsWith('.js') || f.endsWith('.ts');
});//find all js or ts in entities dir
function* importSth() {
for (const f of js_files) {
yield import('./entities/' + f).then((res) => Object.values(res));//import all of them classes
}
}
const entities = (await Promise.all([...importSth()])).flat();
createConnection({
type: 'mysql',
database: 'index',
username: 'root',
password: '123456',
host: 'localhost',
entities, //regist
}) |
try ... "allowSyntheticDefaultImports": true, in tsconfig.json |
When TypeORM tries to load an entity file or a connection config file, it will determine what is the appropriate module system to use for the file and then `import` or `require` it as it sees fit. Closes: typeorm#7516 Closes: typeorm#7159
* feat: support importing TypeORM in esm projects Closes: #6974 Closes: #6941 * bugfix: generate index.mjs directly out of commonjs exports The new implementation generates ESM exports directly out of the commonjs exports, and provides a default export to maintain compatability with existing `import`s of the commonjs implementation * feat: support loading ESM entity and connection config files When TypeORM tries to load an entity file or a connection config file, it will determine what is the appropriate module system to use for the file and then `import` or `require` it as it sees fit. Closes: #7516 Closes: #7159 * fix: adapt ImportUtils.importOrRequireFile tests to older version of nodejs * fix: improved importOrRequireFile implementation * feat: add solution to circular dependency issue in ESM projects * docs: added FAQ regarding ESM projects * chore: add `"type": "commonjs"` to package.json * style * docs: improve `ts-node` usage examples for CLI commands in ESM projects * feat: add support for generating an ESM base project * refactor: renamed `Related` type to `Relation` * docs: added a section in the Getting Started guide regarding the `Relation` wrapper type in ESM projects * docs: improved documentation of the `Relation` type * docs: improved documentation of the `Relation` type * docs: added ESM support to the list of TypeORM features
Issue Description
Error when using TypeORM, and Typescript with folder path
Expected Behavior
As reported here
https://stackoverflow.com/questions/66735359/error-when-using-typeorm-and-typescript-with-folder-path
Entities should load without error.
Currently when using the following tsconfig
and package.json
I get the following error when loading the entities with a string file path -
${process.cwd()}/bin/models/entities/*.js
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ...\Projects\orders-api\bin\models\entities\Address.js
require() of ES modules is not supported.
require() of ...\Projects\orders-api\bin\models\entities\Address.js from ...\Projects\orders-api\node_modules\typeorm\util\DirectoryExportedClassesLoader.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename Address.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from ...
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
Instead rename Address.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\mrivera\Projects\orders-api\package.json.
return createConnection({
name: "default",
type: "mssql",
host: this._server,
username: this._user_name,
password: this._password,
database: this._database,
extra: true,
options: {
isolation: "READ_UNCOMMITTED",
},
entities: [
${this._entity_path}/entities/*.js
],
})
import { Column, Entity, Index, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
import { Patient } from './Patient.js';
import { PatientNextOfKin } from './PatientNextOfKin.js';
@Index("PK__Address__3213E83F7240D5FD", ["id"], { unique: true })
@entity("Address", { schema: "Orders" })
export class Address {
@PrimaryGeneratedColumn({ type: "int", name: "id" })
id!: number;
@column("nvarchar", { name: "line", length: 500 })
line!: string;
@column("nvarchar", { name: "line2", length: 100 })
line2!: string;
@column("nvarchar", { name: "city", length: 100 })
city!: string;
@column("nvarchar", { name: "state", length: 2 })
state!: string;
@column("nvarchar", { name: "zip", length: 10 })
zip!: string;
@OneToMany(() => Patient, (patient) => patient.address)
patients!: Patient[];
@OneToMany(
() => PatientNextOfKin,
(patientNextOfKin) => patientNextOfKin.address
)
patientNextOfKins!: PatientNextOfKin[];
}
The text was updated successfully, but these errors were encountered: