diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index 1fe81450..1ef21f12 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -215,6 +215,49 @@ it('exposes a string as `dependencyMapName` even without collecting dependencies expect(collectDependencies(ast, opts).dependencyMapName).toEqual(any(String)); }); +it('ignores require functions defined defined by lower scopes', () => { + const ast = astFromCode(` + const a = require('b/lib/a'); + exports.do = () => require("do"); + if (!something) { + require("setup/something"); + } + require('do'); + function testA(require) { + const b = require('nonExistantModule'); + } + { + const require = function(foo) { + return; + } + require('nonExistantModule'); + } + `); + const {dependencies, dependencyMapName} = collectDependencies(ast, opts); + expect(dependencies).toEqual([ + {name: 'b/lib/a', isAsync: false}, + {name: 'do', isAsync: false}, + {name: 'setup/something', isAsync: false}, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], 'b/lib/a'); + exports.do = () => require(${dependencyMapName}[1], "do"); + if (!something) { + require(${dependencyMapName}[2], "setup/something"); + } + require(${dependencyMapName}[1], 'do'); + function testA(require) { + const b = require('nonExistantModule'); + } + { + const require = function (foo) { return; }; + require('nonExistantModule'); + } + `), + ); +}); + function astFromCode(code) { return babylon.parse(code, {plugins: ['dynamicImport']}); } diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 0ad9d291..696ed24c 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -74,7 +74,7 @@ function collectDependencies( processImportCall(context, path, node, depMapIdent); return; } - if (isRequireCall(node.callee)) { + if (isNativeRequireCall(path)) { const reqNode = processRequireCall(context, path, node, depMapIdent); visited.add(reqNode); } @@ -88,8 +88,14 @@ function collectDependencies( }; } -function isRequireCall(callee) { - return callee.type === 'Identifier' && callee.name === 'require'; +function isNativeRequireCall(path) { + const node = path.node; + const callee = node.callee; + return ( + callee.type === 'Identifier' && + callee.name === 'require' && + path.scope.bindings['require'] == null + ); } function processImportCall(context, path, node, depMapIdent) {