Skip to content

Commit a66c8c7

Browse files
authored
feat(commonjs): export properties defined using Object.defineProperty(exports, ..) (#222)
* feat: support Object.defineProperty(exports, ..) * chore: rename defineProperty -> isDefinePropertyCall * chore: rename isDefinePropertyCall -> getDefinePropertyCallName
1 parent d8c6ebe commit a66c8c7

File tree

4 files changed

+38
-0
lines changed

4 files changed

+38
-0
lines changed

packages/commonjs/src/transform.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,25 @@ export function checkEsModule(parse, code, id) {
6767
return { isEsModule, hasDefaultExport: false, ast };
6868
}
6969

70+
function getDefinePropertyCallName(node, targetName) {
71+
if (node.type !== 'CallExpression') return;
72+
73+
const {
74+
callee: { object, property }
75+
} = node;
76+
77+
if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
78+
79+
if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
80+
81+
if (node.arguments.length !== 3) return;
82+
83+
const [target, val] = node.arguments;
84+
if (target.type !== 'Identifier' || target.name !== targetName) return;
85+
// eslint-disable-next-line consistent-return
86+
return val.value;
87+
}
88+
7089
export function transformCommonjs(
7190
parse,
7291
code,
@@ -299,6 +318,9 @@ export function transformCommonjs(
299318
return;
300319
}
301320

321+
const name = getDefinePropertyCallName(node, 'exports');
322+
if (name && name === makeLegalIdentifier(name)) namedExports[name] = true;
323+
302324
// if this is `var x = require('x')`, we can do `import x from 'x'`
303325
if (
304326
node.type === 'VariableDeclarator' &&
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Object.defineProperty(exports, "foo", {
2+
enumerable: true,
3+
get: function get() {
4+
return "bar";
5+
}
6+
});
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { foo } from "./foo";

packages/commonjs/test/test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,15 @@ test('does not reexport named contents', async (t) => {
407407
}
408408
});
409409

410+
test(`exports props defined by 'Object.defineProperty'`, async (t) => {
411+
const bundle = await rollup({
412+
input: 'fixtures/samples/define-property/main.js',
413+
plugins: [commonjs()]
414+
});
415+
const m = await executeBundle(bundle, t);
416+
t.is(m.exports.foo, 'bar');
417+
});
418+
410419
test('respects other plugins', async (t) => {
411420
const bundle = await rollup({
412421
input: 'fixtures/samples/other-transforms/main.js',

0 commit comments

Comments
 (0)