Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support default interop for CommonJS macros #9525

Merged
merged 2 commits into from
Feb 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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