Skip to content

Error when mixing ESM and CJS #749

@internettrans

Description

@internettrans

In a project with "type": "module" in the package.json that also contains .cjs files, the .cjs files cannot access the global variables __filename, __dirname, etc that should be available to commonjs files.

I've created https://github.com/joeldenning/ncc-mixed-modules to demonstrate the problem.

~/c/ncc-mixed-modules (main|✔) $ node dist/index.js
file:///Users/joeldenning/code/ncc-mixed-modules/dist/index.js:6
console.log("dep.cjs executing", __filename)
                                 ^

ReferenceError: __filename is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/Users/joeldenning/code/ncc-mixed-modules/dist/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at Object.135 (file:///Users/joeldenning/code/ncc-mixed-modules/dist/index.js:6:34)
    at __nccwpck_require__ (file:///Users/joeldenning/code/ncc-mixed-modules/dist/index.js:32:41)
    at file:///Users/joeldenning/code/ncc-mixed-modules/dist/index.js:52:66
    at file:///Users/joeldenning/code/ncc-mixed-modules/dist/index.js:56:3
    at ModuleJob.run (node:internal/modules/esm/module_job:175:25)
    at async Loader.import (node:internal/modules/esm/loader:178:24)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)
    at async handleMainPromise (node:internal/modules/run_main:63:12)

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions