zazoomauro / node-dependency-injection

The NodeDependencyInjection component allows you to standarize and centralize the way objects are constructed in your application.
https://github.com/zazoomauro/node-dependency-injection/wiki
MIT License
280 stars 34 forks source link

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module #199

Closed kutny closed 1 year ago

kutny commented 1 year ago

Hi, I'm kind of a typescript beginner also coming from the PHP/Symfony world.

Got the following error:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/jirka/projects/page-scraper/src/openai/ClientFactory.ts
require() of ES modules is not supported.
require() of /home/jirka/projects/page-scraper/src/openai/ClientFactory.ts from /home/jirka/projects/page-scraper/node_modules/node-dependency-injection/dist/lib/Loader/FileLoader.js is an ES module file as it is a .ts file whose nearest parent package.json contains "type": "module" which defines all .ts files in that package scope as ES modules.
Instead change the requiring code to use import(), or remove "type": "module" from /home/jirka/projects/page-scraper/package.json.

I have "type": "module" set in package.json

My tsconfig.json

{
  // source https://github.com/wclr/ts-node-dev/issues/314
  "ts-node": {
    "transpileOnly": true,
    "esm": true,
  },
  "compilerOptions": {
    "module": "ESNext",
    "target": "ESNext",
    "rootDir": "src",
    "strict": true,
    "sourceMap": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

services.yaml

services:

  test_service:
    class: "./openai/ClientFactory"
    arguments:
      - "some_key"

Typescript: 5.0.3

running a .ts script using nodemon --experimental-specifier-resolution=node ./src/index.ts

Thanks for your help

zazoomauro commented 1 year ago

This is an issue related with Ts and NodeJs . Not with ndi itself. seems like your are not using import but require or something like this.

zuripabon commented 3 weeks ago

this looks like NDI uses require in FileLoader https://github.com/zazoomauro/node-dependency-injection/blob/cf7b236d440cc2d5a79a6b40798ecc211a770c11/lib/Loader/FileLoader.js#L284 which is not compatible with ESM so looks like no support for ESM as it should use import instead (import is async in ESM so it probably require some major efforts to make NDI ESM compatible)

as an alternative, you might try to use some tooling as esbuild to support cjs in your esm project or import NDI with dynamic import in your esm project (await import('node-dependency-injection'))

hope this helps someone