Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use TypeOrm in nx-nestjs project: ERR_REQUIRE_ESM

I am migrating my NestJS-TypeOrm app to a monorepo (NX workspace).

Whenever I try to run the app, I get this error:

C:\myproject\node_modules\@nrwl\node\src\executors\node\node-with-require-overrides.js:16
return originalLoader.apply(this, arguments);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\myproject\node_modules\@angular\core\fesm2015\core.mjs not supported.
Instead change the require of C:\myproject\node_modules\@angular\core\fesm2015\core.mjs to a dynamic import() which is available in all CommonJS modules.
at Function.Module._load (C:\myproject\node_modules\@nrwl\node\src\executors\node\node-with-require-overrides.js:16:31)
at ...

I debugged for hours and tracked the problem down to the "import" of my entities to TypeOrm, in AppModule:

import {Foo} from './foo.entity.ts';

@Module({
  imports: [
    TypeOrmModule.forRoot({...myConfig, entities: [Foo]}),
    /*...*/
})
export class AppModule {/*...*/}

But also using forFeature() causes the same error:

import {Foo} from './foo.entity.ts';

@Module({
  imports: [TypeOrmModule.forFeature([Foo])],
  /*...*/
})
export class MyFeatureModule {/*...*/}

It seems like the problem might be caused by nx/webpack creating a single main.js file with all the code, whereas before the dist folder contained all the code files seperately.

People suggested using "module": "commonjs" in my tsconfig, or "type": "module" in package.json, but this doesn't do anything :(

Any solution ideas highly appreciated 🙏

like image 547
Patric Avatar asked Jan 20 '26 17:01

Patric


1 Answers

Turns out I'm an idiot. My shared library contained some angular code, and the TypeOrm entities used some enum from that library. Since webpack compiles the whole library in one file, INCLUDING the unused angular code, it then tries to require() an unused angular core module, which obviously fails...

Conclusion: Make sure to extract shared interfaces/enums in a dedicated TS/JS library instead of putting it in an angular library.

like image 76
Patric Avatar answered Jan 23 '26 13:01

Patric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!