Skip to content

Commit

Permalink
Dev-only warning about require cycles in require polyfill
Browse files Browse the repository at this point in the history
Reviewed By: rafeca

Differential Revision: D8928342

fbshipit-source-id: f4ebad5daefd8da6444ca9d6fa1458a338ac7b20
  • Loading branch information
adamjernst authored and facebook-github-bot committed Jul 20, 2018
1 parent 90bf14a commit 8d6b60c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ exports[`basic_bundle bundles package with polyfills 1`] = `
module.isInitialized = false;
module.exports = undefined;
throw e;
}
} finally {}
}
function unknownModuleError(id) {
Expand Down Expand Up @@ -313,7 +313,7 @@ exports[`basic_bundle bundles package without polyfills 1`] = `
module.isInitialized = false;
module.exports = undefined;
throw e;
}
} finally {}
}
function unknownModuleError(id) {
Expand Down
29 changes: 29 additions & 0 deletions packages/metro/src/lib/polyfills/require.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ if (__DEV__) {
[key: string]: number,
__proto__: null,
} = Object.create(null);
var initializingModuleIds: Array<number> = [];
}

function define(
Expand Down Expand Up @@ -146,6 +147,23 @@ function metroRequire(moduleId: ModuleID | VerboseModuleNameForDev) {

//$FlowFixMe: at this point we know that moduleId is a number
const moduleIdReallyIsNumber: number = moduleId;
if (__DEV__) {
const initializingIndex = initializingModuleIds.indexOf(
moduleIdReallyIsNumber,
);
if (initializingIndex !== -1) {
const cycle = initializingModuleIds
.slice(initializingIndex)
.map(id => modules[id].verboseName);
// We want to show A -> B -> A:
cycle.push(cycle[0]);
console.warn(
`Require cycle: ${cycle.join(' -> ')}\n\n` +
'Require cycles are allowed, but can result in uninitialized values. ' +
'Consider refactoring to remove the need for a cycle.',
);
}
}
const module = modules[moduleIdReallyIsNumber];
return module && module.isInitialized
? module.exports
Expand Down Expand Up @@ -222,6 +240,9 @@ function loadModuleImplementation(moduleId, module) {
module.isInitialized = true;
const exports = (module.exports = {});
const {factory, dependencyMap} = module;
if (__DEV__) {
initializingModuleIds.push(moduleId);
}
try {
if (PRINT_REQUIRE_PATHS) {
console.log(`require file path ${module.path || 'unknown'}`); // eslint-disable-line no-console
Expand Down Expand Up @@ -259,6 +280,14 @@ function loadModuleImplementation(moduleId, module) {
module.isInitialized = false;
module.exports = undefined;
throw e;
} finally {
if (__DEV__) {
if (initializingModuleIds.pop() !== moduleId) {
throw new Error(
'initializingModuleIds is corrupt; something is terribly wrong',
);
}
}
}
}

Expand Down

0 comments on commit 8d6b60c

Please sign in to comment.