leinelissen / embedded-postgres

🐘 A Node package that allows you to spawn a Postgresql cluster programatically.
MIT License
53 stars 10 forks source link

'SyntaxError: Cannot use import statement outside a module' when importing EmbeddedPostgres #11

Closed cs97dah closed 6 months ago

cs97dah commented 6 months ago

Hi there,

I'd like to use embedded-postgres in a project I'm on but I've run into a problem when importing the EmbdeddedPostgres class. I see the following error:

(node:90014) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
import EmbeddedPostgres from 'embedded-postgres';
^^^^^^

SyntaxError: Cannot use import statement outside a module

I can recreate this error in a test case with the following steps:

  1. Create an empty directory, start a new project with npm init and accept the defaults
  2. Add the embedded-postgres project with npm install embedded-postgres
  3. Create a file example.js and put the import statement in it: import EmbeddedPostgres from 'embedded-postgres';
  4. Attempt to run the file and I see the error: node example.js

I can't help but think I must have missed something obvious here!

I've tried various other ways to import this but seem to end up with the same error. For example, I tried

const EmbeddedPostgres = require('embedded-postgres').EmbeddedPostgres;

But no luck.

I'm on node version v18.17.0 - is this supported? I saw in the 'development instructions' it says you need to be on v18 or greater, so I hope this is an acceptable version?

If you have any ideas what is up here that would be great as I'd really like to use this library in my project.

Thank you very much.

leinelissen commented 6 months ago

Hi Dean,

embedded-postgres is an ESM package. Hence, if you want to use it, you can only import it if you're using ESM yourself. You can do so by following the suggestions in the error message: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.. It's unfortunate that thing shave to be this way, but supporting both CommonJS and ES Modules at the same time was a significant maintenance burden.

cs97dah commented 6 months ago

Hi Lei, Thanks very much for your quick reply and explanation, really appreciate it. I'm actually very new to the JS ecosystem and hadn't realised there were different module loading mechanisms depending on the target platform. Anyway, thanks again. Cheers, Dean.

leinelissen commented 6 months ago

Yeah it's a mess honestly 😅, it feels very much like the Python 2/3 thing is happening all over again. They're just different enough to not really be compatible, hence I decided to move over to ESM (which should be the future anyway).