Skip to content

Commit d9fb47d

Browse files
authored
fix(commonjs): correctly replace shorthand require (#764)
* fix(commonjs): correctly replace shorthand `require` * fix(commonjs): add comma at the replacement * feat(commonjs): add parent type check for shorthand util
1 parent 03e32d2 commit d9fb47d

File tree

4 files changed

+30
-3
lines changed

4 files changed

+30
-3
lines changed

packages/commonjs/src/ast-utils.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,7 @@ export function isLocallyShadowed(name, scope) {
115115
}
116116
return false;
117117
}
118+
119+
export function isShorthandProperty(parent) {
120+
return parent && parent.type === 'Property' && parent.shorthand;
121+
}

packages/commonjs/src/transform-commonjs.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
isDefineCompiledEsm,
1212
isFalsy,
1313
isReference,
14+
isShorthandProperty,
1415
isTruthy,
1516
KEY_COMPILED_ESM
1617
} from './ast-utils';
@@ -319,10 +320,14 @@ export default function transformCommonjs(
319320
)}`
320321
);
321322
}
323+
if (isShorthandProperty(parent)) {
324+
magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
325+
} else {
326+
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
327+
storeName: true
328+
});
329+
}
322330

323-
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
324-
storeName: true
325-
});
326331
uses.commonjsHelpers = true;
327332
return;
328333
case 'module':
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
const HOST = {
2+
require
3+
};
4+
5+
module.exports = {
6+
HOST
7+
};

packages/commonjs/test/test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -726,6 +726,17 @@ test('does not wrap commonjsRegister calls in createCommonjsModule', async (t) =
726726
t.not(/createCommonjsModule\(function/.test(code), true);
727727
});
728728

729+
test('does not replace shorthand `require` property in object', async (t) => {
730+
const bundle = await rollup({
731+
input: 'fixtures/samples/shorthand-require/main.js',
732+
plugins: [commonjs()]
733+
});
734+
735+
const code = await getCodeFromBundle(bundle, { exports: 'named' });
736+
737+
t.is(/require: commonjsRequire/.test(code), true);
738+
});
739+
729740
// This test uses worker threads to simulate an empty internal cache and needs at least Node 12
730741
if (Number(/^v(\d+)/.exec(process.version)[1]) >= 12) {
731742
test('can be cached across instances', async (t) => {

0 commit comments

Comments
 (0)