Skip to content

[commonjs] Output contains references to __filename #523

@ctjlewis

Description

@ctjlewis
  • Rollup Plugin Name: plugin-commonjs
  • Rollup Plugin Version: 14.0.0
  • Rollup Version: rollup v2.23.0
  • Operating System (or Browser): Ubuntu 20.04
  • Node Version: v14.5.0
  • Link to reproduction (⚠️ read below):
    https://repl.it/@christiantjl/rollup-filename-cjs-esm (use yarn test to get started)

Expected Behavior

With output.format = 'esm', output bundle should:

  1. ❌ Hardcode references to __filename and __dirname (couldn't they be written to a relative version of the output file, i.e. ./output/bundle.mjs here? since everything will be bundled into that spot by definition?)
  2. ✔️ Include ES2015 syntax to export top-level exports in output bundle (this works)
  3. ❌ Not include CJS syntax like module.exports (as seen on repl.it)

Actual Behavior

In my real-life code, I get an error because the ESM output references __filename:

file:///home/christian/Projects/gdev/dev/cli.mjs:14587
  debug$1('initializing', __filename);
                          ^

ReferenceError: __filename is not defined

And on repl.it, in addition to ESM output containing _filename, the output also includes a module.exports declaration at the top, which throws an error immediately:

output/bundle.mjs

module.exports = {
  test: __filename
};

var test = /*#__PURE__*/Object.freeze({
  __proto__: null
});

/**
 * Import a CJS module, log it, export it.
 */

console.log(test);

var index = {
  test
};

/**
 * `node index.mjs` or `node .` prints (as expected):
 *
 * [Module] {
 *   default: { test: '/home/runner/rollup-filename-cjs-esm/importme.cjs' }
 * }
 */

export default index;

Additional Information

Any advice related to working around the __filename error is especially appreciated, I expect the inclusion of module.exports at the top of the repl.it bundle is related to the lower Node version, but I figured I would point that out.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions