Skip to content

Commit

Permalink
feat(core): conditionally support folder based discovery of ESM
Browse files Browse the repository at this point in the history
By setting `MIKRO_ORM_DYNAMIC_IMPORTS` we now get a dynamic import even
tho we still compile to CommonJS. This enabled support for folder based
discovery when using ES modules.

Related: #2631
  • Loading branch information
B4nan committed Jan 12, 2022
1 parent c680295 commit 8c8f0d0
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 4 deletions.
4 changes: 2 additions & 2 deletions packages/core/src/metadata/MetadataDiscovery.ts
Expand Up @@ -959,7 +959,7 @@ export class MetadataDiscovery {

private async initEnumValues(prop: EntityProperty, path: string): Promise<void> {
path = Utils.normalizePath(this.config.get('baseDir'), path);
const exports = await import(path);
const exports = await Utils.dynamicImport(path);
const target = exports[prop.type] || exports.default;

if (target) {
Expand Down Expand Up @@ -994,7 +994,7 @@ export class MetadataDiscovery {
}

private async getEntityClassOrSchema(path: string, name: string) {
const exports = await import(path);
const exports = await Utils.dynamicImport(path);
const targets = Object.values<Dictionary>(exports)
.filter(item => item instanceof EntitySchema || (item instanceof Function && MetadataStorage.isKnownEntity(item.name)));

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/utils/ConfigurationLoader.ts
Expand Up @@ -21,7 +21,7 @@ export class ConfigurationLoader {
path = Utils.normalizePath(path);

if (await pathExists(path)) {
const config = await import(path);
const config = await Utils.dynamicImport(path);
/* istanbul ignore next */
let tmp = config.default ?? config;

Expand Down
14 changes: 14 additions & 0 deletions packages/core/src/utils/Utils.ts
Expand Up @@ -752,6 +752,20 @@ export class Utils {
return createRequire(resolve(from))(id);
}

/**
* Hack to keep dynamic imports even when compiling to CJS.
* We can't use it always, as it would break ts-node.
* @see https://github.com/microsoft/TypeScript/issues/43329#issuecomment-922544562
*/
static async dynamicImport<T = any>(id: string): Promise<T> {
if (!process.env.MIKRO_ORM_DYNAMIC_IMPORTS) {
return import(id);
}

/* istanbul ignore next */
return Function(`return import('${id}')`)();
}

static getORMVersion(): string {
/* istanbul ignore next */
try {
Expand Down
1 change: 0 additions & 1 deletion tests/EntityManager.mysql.test.ts
Expand Up @@ -13,7 +13,6 @@ import { Author2Subscriber } from './subscribers/Author2Subscriber';
import { EverythingSubscriber } from './subscribers/EverythingSubscriber';
import { FlushSubscriber } from './subscribers/FlushSubscriber';
import { Test2Subscriber } from './subscribers/Test2Subscriber';
import { ManualAuthor2Subscriber } from './subscribers/ManualAuthor2Subscriber';

describe('EntityManagerMySql', () => {

Expand Down

0 comments on commit 8c8f0d0

Please sign in to comment.