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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(commonjs): correctly replace shorthand require #764

Merged
merged 3 commits into from Jan 29, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions packages/commonjs/src/ast-utils.js
Expand Up @@ -115,3 +115,7 @@ export function isLocallyShadowed(name, scope) {
}
return false;
}

export function isShorthandProperty(parent) {
return parent && parent.shorthand;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please can you check parent.type is the correct value too?

}
11 changes: 8 additions & 3 deletions packages/commonjs/src/transform-commonjs.js
Expand Up @@ -11,6 +11,7 @@ import {
isDefineCompiledEsm,
isFalsy,
isReference,
isShorthandProperty,
isTruthy,
KEY_COMPILED_ESM
} from './ast-utils';
Expand Down Expand Up @@ -234,10 +235,14 @@ export default function transformCommonjs(
)}`
);
}
if (isShorthandProperty(parent)) {
magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
} else {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
storeName: true
});
}

magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
storeName: true
});
uses.commonjsHelpers = true;
return;
case 'module':
Expand Down
@@ -0,0 +1,7 @@
const HOST = {
require
};

module.exports = {
HOST
};
11 changes: 11 additions & 0 deletions packages/commonjs/test/test.js
Expand Up @@ -726,6 +726,17 @@ test('does not wrap commonjsRegister calls in createCommonjsModule', async (t) =
t.not(/createCommonjsModule\(function/.test(code), true);
});

test('does not replace shorthand `require` property in object', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/shorthand-require/main.js',
plugins: [commonjs()]
});

const code = await getCodeFromBundle(bundle, { exports: 'named' });

t.is(/require: commonjsRequire/.test(code), true);
});

// This test uses worker threads to simulate an empty internal cache and needs at least Node 12
if (Number(/^v(\d+)/.exec(process.version)[1]) >= 12) {
test('can be cached across instances', async (t) => {
Expand Down