Skip to content

Commit

Permalink
Find nested exports when inside ternary
Browse files Browse the repository at this point in the history
Some libraries (like airbnb-prop-types [1]), like to export different
files depending the current NODE_ENV. Export statements can then look
something like:

  module.exports = process.env.NODE_ENV === 'production' ?
    require('a') : require('b');

In most cases, the two alternatives will have the same structure, so
finding named exports in either of the two should be fine.

I've made it so that we always pick the first alternative (the
`consequent`) in ternary exports.

There are of course other ways of conditionally exporting things. For
now I'm only dealing with ternaries, we can worry about other styles
when we have those use-cases.

Fixes #411

[1] https://unpkg.com/airbnb-prop-types@2.5.4
  • Loading branch information
trotzig committed Jun 5, 2017
1 parent 18d4dcd commit 828b46a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
21 changes: 17 additions & 4 deletions lib/__tests__/findExports-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -441,18 +441,31 @@ it('does not fail for inner exports that are not objects', () => {
});

describe('recursive exports', () => {
it('follows exported requires', () => {
beforeEach(() => {
fs.__setFile(
'/path/to/foo.js',
'const Result = { bar: 123 }; module.exports = Result;',
{ isDirectory: () => false },
);
requireRelative.resolve.mockImplementation(() => '/path/to/foo.js');
});

it('follows exported requires', () => {
expect(
findExports("module.exports = require('./foo');", '/path/to/file.js'),
).toEqual({
named: ['bar'],
hasDefault: true,
});
});

it('picks the first require if inside a ternary', () => {
expect(
findExports(
`
module.exports = require('./foo');
`,
`
module.exports = process.env.NODE_ENV === 'test' ?
require('./foo') : require('./ignored');
`,
'/path/to/file.js',
),
).toEqual({
Expand Down
5 changes: 5 additions & 0 deletions lib/findExports.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ function findESNamedExports(node) {
}

function resolveNestedNamedExports(node, absolutePathToFile) {
if (node.type === 'ConditionalExpression') {
// Potential ternary-style export - we pick the first one
// module.exports = foo ? require('a') : require('b');
return resolveNestedNamedExports(node.consequent, absolutePathToFile);
}
if (
node.type === 'CallExpression' &&
node.callee.name === 'require' &&
Expand Down

0 comments on commit 828b46a

Please sign in to comment.