Search code examples
webpacknestjstypeormmonoreponrwl-nx

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 🙏


Solution

  • 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.