Skip to content

Commit

Permalink
feat(commonjs): export properties defined using Object.defineProperty…
Browse files Browse the repository at this point in the history
…(exports, ..) (#222)

* feat: support Object.defineProperty(exports, ..)

* chore: rename defineProperty -> isDefinePropertyCall

* chore: rename isDefinePropertyCall -> getDefinePropertyCallName
  • Loading branch information
edeustace authored Feb 29, 2020
1 parent d8c6ebe commit a66c8c7
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/commonjs/src/transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,25 @@ export function checkEsModule(parse, code, id) {
return { isEsModule, hasDefaultExport: false, ast };
}

function getDefinePropertyCallName(node, targetName) {
if (node.type !== 'CallExpression') return;

const {
callee: { object, property }
} = node;

if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;

if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;

if (node.arguments.length !== 3) return;

const [target, val] = node.arguments;
if (target.type !== 'Identifier' || target.name !== targetName) return;
// eslint-disable-next-line consistent-return
return val.value;
}

export function transformCommonjs(
parse,
code,
Expand Down Expand Up @@ -299,6 +318,9 @@ export function transformCommonjs(
return;
}

const name = getDefinePropertyCallName(node, 'exports');
if (name && name === makeLegalIdentifier(name)) namedExports[name] = true;

// if this is `var x = require('x')`, we can do `import x from 'x'`
if (
node.type === 'VariableDeclarator' &&
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Object.defineProperty(exports, "foo", {
enumerable: true,
get: function get() {
return "bar";
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { foo } from "./foo";
9 changes: 9 additions & 0 deletions packages/commonjs/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,15 @@ test('does not reexport named contents', async (t) => {
}
});

test(`exports props defined by 'Object.defineProperty'`, async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/define-property/main.js',
plugins: [commonjs()]
});
const m = await executeBundle(bundle, t);
t.is(m.exports.foo, 'bar');
});

test('respects other plugins', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/other-transforms/main.js',
Expand Down

0 comments on commit a66c8c7

Please sign in to comment.