Skip to content

getCjsExportFromNamespace messes up default exports #491

Closed
@Veetaha

Description

@Veetaha
  • Rollup Plugin Name: @rollup/plugin-commonjs
  • Rollup Plugin Version: 13.0.0
  • Rollup Version: 2.18.1
  • Operating System (or Browser): Vscode extension host (I guess it is bare nodejs process)
  • Node Version: 12.8.1

How Do We Reproduce?

Link to REPL

Use the following rollup.config.js:

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import nodeBuiltins from 'builtin-modules';

export default {
    input: 'out/src/main.js',
    plugins: [
        resolve({
            preferBuiltins: true
        }),
        commonjs()
    ],
    external: [...nodeBuiltins, 'vscode'],
    output: {
        file: './out/src/main.js',
        format: 'cjs'
    }
};

Add "node-fetch": "^2.6.0" to package.json
Write the following code (in reality it is generated by tsc as the first step before invoking rollup):

const fetch = require("node-fetch");
console.log(typeof fetch.default);

When run in node REPL this works fine:

Output
$ node
Welcome to Node.js v14.4.0.
Type ".help" for more information.
> const fetch = require("node-fetch");
undefined
> console.log(typeof fetch.default)
function

Expected Behavior

When packaged with rollup it must work the same as in node REPL (it must not crash in our production!)

Actual Behavior

It outputs undefined.
The reason is that the bundle contains the following:

function getCjsExportFromNamespace (n) {
	return n && n['default'] || n;  // <--- this is the culprit
}

var lib = /*#__PURE__*/Object.freeze({
	__proto__: null,
	'default': fetch,
	Headers: Headers,
	Request: Request,
	Response: Response,
	FetchError: FetchError
});

var fetch = getCjsExportFromNamespace(lib);

console.log(typeof fetch.default);

cc @lukastaegert
related: rust-lang/rust-analyzer#5257 (comment)

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