Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

preserve require.context call when unstable_disableModuleWrapping is enabled #1129

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/metro-transform-worker/src/index.js
Expand Up @@ -370,6 +370,7 @@ async function transformJS(
allowOptionalDependencies: config.allowOptionalDependencies,
dependencyMapName: config.unstable_dependencyMapReservedName,
unstable_allowRequireContext: config.unstable_allowRequireContext,
unstable_disableModuleWrapping: config.unstable_disableModuleWrapping,
};
({ast, dependencies, dependencyMapName} = collectDependencies(ast, opts));
} catch (error) {
Expand Down
Expand Up @@ -40,6 +40,7 @@ const opts: Options = {
allowOptionalDependencies: false,
dependencyMapName: null,
unstable_allowRequireContext: false,
unstable_disableModuleWrapping: false,
};

describe(`require.context`, () => {
Expand Down
11 changes: 9 additions & 2 deletions packages/metro/src/ModuleGraph/worker/collectDependencies.js
Expand Up @@ -93,6 +93,8 @@ export type Options = $ReadOnly<{
dependencyTransformer?: DependencyTransformer,
/** Enable `require.context` statements which can be used to import multiple files in a directory. */
unstable_allowRequireContext: boolean,

unstable_disableModuleWrapping?: ?boolean,
}>;

export type CollectedDependencies = $ReadOnly<{
Expand Down Expand Up @@ -192,6 +194,13 @@ function collectDependencies(
!path.scope.getBinding('require')
) {
processRequireContextCall(path, state);
// If module wrapping is disabled then we shouldn't mutate the AST,
// this enables calling collectDependencies multiple times on the same
// AST.
if (!options.unstable_disableModuleWrapping) {
// require() the generated module representing this context
path.get('callee').replaceWith(types.identifier('require'));
}
visited.add(path.node);
return;
}
Expand Down Expand Up @@ -387,8 +396,6 @@ function processRequireContextCall(
path,
);

// require() the generated module representing this context
path.get('callee').replaceWith(types.identifier('require'));
transformer.transformSyncRequire(path, dep, state);
}

Expand Down