diff --git a/packages/commonjs/src/ast-utils.js b/packages/commonjs/src/ast-utils.js index a699c57a6..253f20f86 100644 --- a/packages/commonjs/src/ast-utils.js +++ b/packages/commonjs/src/ast-utils.js @@ -115,3 +115,7 @@ export function isLocallyShadowed(name, scope) { } return false; } + +export function isShorthandProperty(parent) { + return parent && parent.type === 'Property' && parent.shorthand; +} diff --git a/packages/commonjs/src/transform-commonjs.js b/packages/commonjs/src/transform-commonjs.js index f533b2530..c41937124 100644 --- a/packages/commonjs/src/transform-commonjs.js +++ b/packages/commonjs/src/transform-commonjs.js @@ -11,6 +11,7 @@ import { isDefineCompiledEsm, isFalsy, isReference, + isShorthandProperty, isTruthy, KEY_COMPILED_ESM } from './ast-utils'; @@ -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': diff --git a/packages/commonjs/test/fixtures/samples/shorthand-require/main.js b/packages/commonjs/test/fixtures/samples/shorthand-require/main.js new file mode 100644 index 000000000..c42befeb5 --- /dev/null +++ b/packages/commonjs/test/fixtures/samples/shorthand-require/main.js @@ -0,0 +1,7 @@ +const HOST = { + require +}; + +module.exports = { + HOST +}; diff --git a/packages/commonjs/test/test.js b/packages/commonjs/test/test.js index 70a092bc6..dee5c38b6 100644 --- a/packages/commonjs/test/test.js +++ b/packages/commonjs/test/test.js @@ -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) => {