ReferenceError: exports is not defined in ES module scope

I am trying to run my bot and am presented with the following error

Successfully compiled: 13 files with swc (25.27ms)
Debugger listening on ws://0.0.0.0:9229/db93ad55-46aa-4ed1-be89-f2b2b5cded3b
For help, see: https://nodejs.org/en/docs/inspector
file:///home/demonicpagan/development/nodejs/discordBots/discord-trakt/dist/bot.js:2
Object.defineProperty(exports, "__esModule", {
                      ^

ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/home/demonicpagan/development/nodejs/discordBots/discord-trakt/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///home/demonicpagan/development/nodejs/discordBots/discord-trakt/dist/bot.js:2:23
    at ModuleJob.run (node:internal/modules/esm/module_job:217:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)
    at async loadESM (node:internal/process/esm_loader:34:7)
    at async handleMainPromise (node:internal/modules/run_main:66:12)

Node.js v20.9.0
 ELIFECYCLE  Command failed with exit code 1.


What do I need to do to resolve this?

Since there are so many files involved and the length would exceed the Discord limitations, I created a gist with everything I think is needed.

https://gist.github.com/dustin-lennon/30bee1b477e4de8dae3459f4fa4c6b96
Gist
ReferenceError: exports is not defined in ES module scope - TraktClient.ts
ReferenceError: exports is not defined in ES module scope
Solution
so when using pnpm you need to hoist all of
@sapphire/*
because otherwise TS cannot properly resolve module augmentations. I forgot the exact option but it's one of the hoist pattern options.

As for your root cause, it really comes down to how you configured tsconfig. The modern standard is to use
node16
for both
module
and
moduleResolution
then either use
"type": "commonjs"
or
"type": "module"
in your package.json based on whether you respectively want a CJS or ESM runtime.

Once that is done and you compile with either exclusively swc (which you seem to use yet you also mention ts-node, they DO NOT work together, also we discussed the downsides of ts-node) or alternatives such as
tsc
/
tsc-watch
/
tsup
.

The error in particular suggests that you compiled for CJS but are running as ESM (i.e. you specified
"type": "module"
in your package.json) which causes the error of
exports
not being defined in an ES module (ESM) scope. So either change your compilation to ESM, or change
"type": "module"
to "
type": "commonjs
.
Was this page helpful?