Skip to content

Commit

Permalink
Support default interop for CommonJS macros (#9525)
Browse files Browse the repository at this point in the history
  • Loading branch information
devongovett committed Feb 11, 2024
1 parent a93af6a commit e14784d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/core/integration-tests/test/macros.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,28 @@ describe('macros', function () {
assert(res.includes('output="2a2300bbd7ea6e9a"'));
});

it('should support default interop with CommonJS modules', async function () {
await fsFixture(overlayFS, dir)`
index.js:
import test from "./macro.js" with { type: "macro" };
output = test('hi');
macro.js:
import {hashString} from '@parcel/rust';
module.exports = function(s) {
return hashString(s);
}
`;

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

let res = await overlayFS.readFile(b.getBundles()[0].filePath, 'utf8');
assert(res.includes('output="2a2300bbd7ea6e9a"'));
});

it('should support namespace imports', async function () {
await fsFixture(overlayFS, dir)`
index.js:
Expand Down
11 changes: 11 additions & 0 deletions packages/transformers/js/src/JSTransformer.js
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,17 @@ export default (new Transformer({
let mod;
try {
mod = await options.packageManager.require(src, asset.filePath);

// Default interop for CommonJS modules.
if (
exportName === 'default' &&
!mod.__esModule &&
// $FlowFixMe
Object.prototype.toString.call(config) !== '[object Module]'
) {
mod = {default: mod};
}

if (!Object.hasOwnProperty.call(mod, exportName)) {
throw new Error(`"${src}" does not export "${exportName}".`);
}
Expand Down

0 comments on commit e14784d

Please sign in to comment.