Skip to content

Commit

Permalink
Traverse block statements when looking for dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
yuchi committed Nov 29, 2018
1 parent af8279f commit a267cf5
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
32 changes: 32 additions & 0 deletions src/__snapshots__/hooks.spec.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,38 @@ function FakeComponent(_ref) {
"
`;

exports[`Hooks macro › Is not confused by block scopes: Is not confused by block scopes 1`] = `
"
import { useAutoMemo } from './hooks.macro'
function FakeComponent({ propValue = 2 }) {
const outer = 3;
{
const inner = 7;
const result = useAutoMemo(outer * inner * propValue);
}
}
↓ ↓ ↓ ↓ ↓ ↓
\\"use strict\\";
var _react = require(\\"react\\");
function FakeComponent(_ref) {
var _ref$propValue = _ref.propValue,
propValue = _ref$propValue === void 0 ? 2 : _ref$propValue;
var outer = 3;
{
var inner = 7;
var result = (0, _react.useMemo)(function () {
return outer * inner * propValue;
}, [outer, inner, propValue]);
}
}
"
`;

exports[`Hooks macro › Skips globals: Skips globals 1`] = `
"
import { useAutoMemo } from './hooks.macro'
Expand Down
13 changes: 12 additions & 1 deletion src/hooks.macro.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ const { createMacro } = require('babel-plugin-macros');

module.exports = createMacro(memoMacro);

function reachSignificantScope(t, scope) {
while (scope.path.parentPath && t.isBlockStatement(scope.path)) {
scope = scope.path.parentPath.scope;
}

return scope;
}

function visitInputsReferences(parentPath, entryPath, babel, visitor) {
const { types: t } = babel;

Expand All @@ -22,7 +30,10 @@ function visitInputsReferences(parentPath, entryPath, babel, visitor) {
}

// Excluding bindings outside of the component
if (binding.scope !== parentScope) {
if (
reachSignificantScope(t, binding.scope) !==
reachSignificantScope(t, parentScope)
) {
return;
}

Expand Down
14 changes: 14 additions & 0 deletions src/hooks.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,20 @@ pluginTester({
}
`,
},
{
title: 'Is not confused by block scopes',
code: `
import { useAutoMemo } from './hooks.macro'
function FakeComponent({ propValue = 2 }) {
const outer = 3;
{
const inner = 7;
const result = useAutoMemo(outer * inner * propValue);
}
}
`,
},
{
title: 'Does not create a double require() with named hook import',
code: `
Expand Down

0 comments on commit a267cf5

Please sign in to comment.