Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/commonjs/src/ast-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,7 @@ export function isLocallyShadowed(name, scope) {
}
return false;
}

export function isShorthandProperty(parent) {
return parent && parent.type === 'Property' && parent.shorthand;
}
11 changes: 8 additions & 3 deletions packages/commonjs/src/transform-commonjs.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const HOST = {
require
};

module.exports = {
HOST
};
11 changes: 11 additions & 0 deletions packages/commonjs/test/test.js
Original file line number Diff line number Diff line change
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