GiovanniCardamone / fastify-autoroutes

fastest way to map directories to URLs in fastify
https://giovannicardamone.github.io/fastify-autoroutes/
MIT License
85 stars 12 forks source link

[QUESTION] How to import with ES modules? #201

Open go4cas opened 1 year ago

go4cas commented 1 year ago

I can seem to get the package working correctly when using ES modules:

server.js:

...
import autoroutes from 'fastify-autoroutes'
...
...
  try {
    await server.register(autoroutes, {
      dir:'./routes',
    })
  } catch (error) {
    console.log('ERROR:', error)
  }
...

When the server is started, the following exception: "Error [ERR_REQUIRE_ESM]: require() of ES Module .../src/routes/index.js from .../node_modules/fastify-autoroutes/dist/index.js not supported"

GiovanniCardamone commented 1 year ago

internally this plugin use require to import modules, i should replace with await import to make it works with es modules.

Not sure i will support this, this plugin was intended to work with commonjs or typescript.

I need to do some tests to ensure this change won't break current behaivour.

go4cas commented 1 year ago

Thanks, @GiovanniCardamone! In the meantime, I have used @emil-1996's suggestion on https://github.com/GiovanniCardamone/fastify-autoroutes/issues/190#issuecomment-1120184645, to create a local plugin. It works well in ES modules.

Thanks for the great plugin!

JREAM commented 1 year ago

Ah, this is where I ended up. Bummer!

GiovanniCardamone commented 1 year ago

Okay, I think I will support this using a bundler like tsup to create a cjs and a mjs output.

Be patient with this, I'm in a pretty busy situation 😅