Skip to content

Commit e825d59

Browse files
authored
Fix CJS default interop with library bundler (#9722)
1 parent 38635b5 commit e825d59

File tree

2 files changed

+58
-2
lines changed

2 files changed

+58
-2
lines changed

packages/core/integration-tests/test/library-bundler.js

+47
Original file line numberDiff line numberDiff line change
@@ -578,4 +578,51 @@ describe('library bundler', function () {
578578
assert(!contents.includes('../'));
579579
}
580580
});
581+
582+
it('should support export default in CJS', async () => {
583+
await fsFixture(overlayFS, dir)`
584+
yarn.lock:
585+
586+
.parcelrc:
587+
{
588+
"extends": "@parcel/config-default",
589+
"bundler": "@parcel/bundler-library"
590+
}
591+
592+
package.json:
593+
{
594+
"module": "dist/module.js",
595+
"main": "dist/main.js",
596+
"engines": { "node": "*" }
597+
}
598+
599+
index.js:
600+
import foo from './foo';
601+
export function test() {
602+
return 'test:' + foo();
603+
}
604+
605+
foo.js:
606+
export default function foo() {
607+
return 'foo';
608+
}
609+
`;
610+
611+
let b = await bundle(dir + '/index.js', {
612+
inputFS: overlayFS,
613+
mode: 'production',
614+
});
615+
616+
let esm: any = await runBundle(
617+
b,
618+
nullthrows(b.getBundles().find(b => b.name === 'module.js')),
619+
);
620+
assert.equal(esm.test(), 'test:foo');
621+
622+
let cjs: any = await runBundle(
623+
b,
624+
nullthrows(b.getBundles().find(b => b.name === 'main.js')),
625+
);
626+
assert.equal(cjs.test(), 'test:foo');
627+
});
581628
});

packages/packagers/js/src/ScopeHoistingPackager.js

+11-2
Original file line numberDiff line numberDiff line change
@@ -828,8 +828,17 @@ ${code}
828828
if (imported === '*') {
829829
replacement = renamed;
830830
} else if (imported === 'default') {
831-
replacement = `($parcel$interopDefault(${renamed}))`;
832-
this.usedHelpers.add('$parcel$interopDefault');
831+
let needsDefaultInterop = true;
832+
if (referencedBundle) {
833+
let entry = nullthrows(referencedBundle.getMainEntry());
834+
needsDefaultInterop = this.needsDefaultInterop(entry);
835+
}
836+
if (needsDefaultInterop) {
837+
replacement = `($parcel$interopDefault(${renamed}))`;
838+
this.usedHelpers.add('$parcel$interopDefault');
839+
} else {
840+
replacement = `${renamed}.default`;
841+
}
833842
} else {
834843
replacement = this.getPropertyAccess(renamed, imported);
835844
}

0 commit comments

Comments
 (0)