Skip to content

Commit

Permalink
Fix CJS default interop with library bundler
Browse files Browse the repository at this point in the history
  • Loading branch information
devongovett committed May 17, 2024
1 parent 25d010a commit 1f9adfe
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
47 changes: 47 additions & 0 deletions packages/core/integration-tests/test/library-bundler.js
Original file line number Diff line number Diff line change
Expand Up @@ -578,4 +578,51 @@ describe('library bundler', function () {
assert(!contents.includes('../'));
}
});

it('should support export default in CJS', async () => {
await fsFixture(overlayFS, dir)`
yarn.lock:
.parcelrc:
{
"extends": "@parcel/config-default",
"bundler": "@parcel/bundler-library"
}
package.json:
{
"module": "dist/module.js",
"main": "dist/main.js",
"engines": { "node": "*" }
}
index.js:
import foo from './foo';
export function test() {
return 'test:' + foo();
}
foo.js:
export default function foo() {
return 'foo';
}
`;

let b = await bundle(dir + '/index.js', {
inputFS: overlayFS,
mode: 'production',
});

let esm: any = await runBundle(
b,
nullthrows(b.getBundles().find(b => b.name === 'module.js')),
);
assert.equal(esm.test(), 'test:foo');

let cjs: any = await runBundle(
b,
nullthrows(b.getBundles().find(b => b.name === 'main.js')),
);
assert.equal(cjs.test(), 'test:foo');
});
});
13 changes: 11 additions & 2 deletions packages/packagers/js/src/ScopeHoistingPackager.js
Original file line number Diff line number Diff line change
Expand Up @@ -828,8 +828,17 @@ ${code}
if (imported === '*') {
replacement = renamed;
} else if (imported === 'default') {
replacement = `($parcel$interopDefault(${renamed}))`;
this.usedHelpers.add('$parcel$interopDefault');
let needsDefaultInterop = true;
if (referencedBundle) {
let entry = nullthrows(referencedBundle.getMainEntry());
needsDefaultInterop = this.needsDefaultInterop(entry);
}
if (needsDefaultInterop) {
replacement = `($parcel$interopDefault(${renamed}))`;
this.usedHelpers.add('$parcel$interopDefault');
} else {
replacement = `${renamed}.default`;
}
} else {
replacement = this.getPropertyAccess(renamed, imported);
}
Expand Down

0 comments on commit 1f9adfe

Please sign in to comment.