planetscale/database-js

Error [ERR_REQUIRE_ESM]: require() of ES Module

ethereumdegen opened this issue · 3 comments

Trying to use in my typescript project and i get

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/.../dev/...-monorepo/node_modules/@planetscale/database/dist/index.js from /home/.../dev/...-monorepo/...-backend/db/client.ts not supported.
Instead change the require of index.js in /home/.../dev/...-monorepo/...-backend/db/client.ts to a dynamic import() which is available in all CommonJS modules.

See #67 for how to use a dynamic import rather than require.

For those stuck with typescript / eslint / whatever and needing to ship or fix the bug fast:

You can just copy over the repository to your src files and import it, it has zero dependencies:

image

@dgraham For ts-node users, using a dynamic import is a painful solution. That's because top-level await is close to impossible to get working without breaking a bunch of other things.

In my case, if I want to use database-js in my project, I will have to export a promise that resolves into the connection object and refactor every import of it in my project (hundreds), including the code which depends on it, to be wrapped within e.g. an async IIFE so that the conn object import promise can be awaited before use. Ouch!

To avoid this, I'm forced to go with the above solution of just downloading the repo's source into my codebase... :/

A CJS module would make a huge difference in the meantime while the sluggish JS modules ecosystem catches up! I found a great guide for how to support both CJS and ESM: https://evertpot.com/universal-commonjs-esm-typescript-packages/