#Can I use ES Modules with payload somehow?

11 messages · Page 1 of 1 (latest)

last folio
#

I have a sveltekit app I want to run with payload's express server. I'm doing

import { handler } from "mysvelteproject/handler.js";
const app = express();
....
app.use(handler)

However I get the following error when I build and try to run the server

var handler_js_1 = require("mysvelteproject/handler.js");
                   ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /Projects/cms/node_modules/mysvelteproject/handler.js from /Projects/cms/dist/server.js not supported.

What I've tried:
Following this post https://discord.com/channels/967097582721572934/1196752494722830376 I changed the tsconfig from "target":"es5" to

"target": "esnext",
"module": "ESNext",
"moduleResolution": "Bundler",

And I changed nodemon.json from using ts-node to tsx "exec": "tsx src/server.ts -- -I"

This almost works. I can do npm run dev and everything runs and works perfectly. However doing npm run build and trying to run the server I get this error now

/Projects/cms/node_modules/payload/dist/config/load.js:28
    const configPromise = require(configPath);
                          ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /Projects/cms/dist/payload.config.js from /Projects/cms/node_modules/payload/dist/config/load.js not supported.
Instead change the require of payload.config.js in /Projects/cms/node_modules/payload/dist/config/load.js to a dynamic import() which is available in all CommonJS modules.

I've also tried all combinations of adding/removing "type":"module" in my svelte and payload project's package.json.

I would really really appreciate any help or guidance here. I've been tearing my head out for the past 3 days with this and I'm out of ideas on what to try.

slim scaffoldBOT
sour tendon
#

I had the same issue, and I don't think it's possible to use payload currently in ESM, everything must be commonjs.

However payload v3 (in beta) will be esm-first, so you might look into migrating

last folio
#

Ah that's sad to hear FeelsBadMan
I wonder why running it with tsx works fine? I had hoped that meant there was a way

sly nexus
#

@last folio Which version of node.js are you on? 21.x has breaking changes on breaking boundaries between ES and CommonJS modules. I recommend to upgrade node.js version up to 21

last folio
sly nexus
#

Oh, you are already on the latest version. then node version won't matter

last folio
#

ah okay

mossy knot
#

If you wanna import ESM within payload, either upgrade to payload 3.0 or try out Bun as a runtime (might work in 2.0)

#

Anything else would be a nightmare

last folio