Skip to content

Commit

Permalink
fix: correctly wraps the default export from a CommonJS module when i…
Browse files Browse the repository at this point in the history
…t is a class

Fixes https://github.com/vitejs/vite/issues/10853

Since rollup@3c00191
the namespace became callable when requiring ESM with function default,
but it isn't newable, leading to errors when the function is actually a
class.
  • Loading branch information
haoqunjiang committed Nov 19, 2022
1 parent 570f77c commit 32cd0c8
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/commonjs/src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,13 @@ export function getDefaultExportFromNamespaceIfNotNamed (n) {
export function getAugmentedNamespace(n) {
var f = n.default;
if (typeof f == "function") {
var a = function () {
var a = function a () {
if (this instanceof a) {
var args = [null];
args.push.apply(args, arguments);
var Ctor = Function.bind.apply(f, args);
return new Ctor();
}
return f.apply(this, arguments);
};
a.prototype = f.prototype;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const Foo = require('./other.js');

new Foo(1, 2)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default class Foo {
constructor(...args) {
if (args.length !== 2) {
throw new Error(`new Foo(...) requires exactly 2 arguments, received ${args.length}`);
}
}
}
9 changes: 9 additions & 0 deletions packages/commonjs/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,15 @@ test('prefers to set name using directory for index files', async (t) => {
t.not(code.indexOf('var nonIndex'), -1, 'contains nonIndex');
});

test('correctly wraps the default export from a CommonJS module when it is a class', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/es-module-with-class-as-default-export/main.js',
plugins: [commonjs()]
});
const result = await executeBundle(bundle, t);
t.is(result.error, undefined);
});

test('does not warn even if the ES module does not export "default"', async (t) => {
const warns = [];
await rollup({
Expand Down

0 comments on commit 32cd0c8

Please sign in to comment.