diff --git a/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap b/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap index a5773cfe52..f43f282a5e 100644 --- a/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap +++ b/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap @@ -131,6 +131,7 @@ Object { "transformVariants": Object { "default": Object {}, }, + "unstable_allowRequireContext": false, "unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js", "unstable_compactOutput": false, "unstable_dependencyMapReservedName": null, @@ -276,6 +277,7 @@ Object { "transformVariants": Object { "default": Object {}, }, + "unstable_allowRequireContext": false, "unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js", "unstable_compactOutput": false, "unstable_dependencyMapReservedName": null, @@ -421,6 +423,7 @@ Object { "transformVariants": Object { "default": Object {}, }, + "unstable_allowRequireContext": false, "unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js", "unstable_compactOutput": false, "unstable_dependencyMapReservedName": null, @@ -566,6 +569,7 @@ Object { "transformVariants": Object { "default": Object {}, }, + "unstable_allowRequireContext": false, "unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js", "unstable_compactOutput": false, "unstable_dependencyMapReservedName": null, diff --git a/packages/metro-config/src/defaults/index.js b/packages/metro-config/src/defaults/index.js index 55a0b95376..316f503464 100644 --- a/packages/metro-config/src/defaults/index.js +++ b/packages/metro-config/src/defaults/index.js @@ -119,6 +119,7 @@ const getDefaultValues = (projectRoot: ?string): ConfigT => ({ workerPath: 'metro/src/DeltaBundler/Worker', publicPath: '/assets', allowOptionalDependencies: false, + unstable_allowRequireContext: false, unstable_collectDependenciesPath: 'metro/src/ModuleGraph/worker/collectDependencies.js', unstable_dependencyMapReservedName: null, diff --git a/packages/metro-transform-worker/src/__tests__/index-test.js b/packages/metro-transform-worker/src/__tests__/index-test.js index 0c2f357968..ab6e3e22a4 100644 --- a/packages/metro-transform-worker/src/__tests__/index-test.js +++ b/packages/metro-transform-worker/src/__tests__/index-test.js @@ -65,6 +65,7 @@ const baseConfig: JsTransformerConfig = { unstable_compactOutput: false, unstable_disableModuleWrapping: false, unstable_disableNormalizePseudoGlobals: false, + unstable_allowRequireContext: false, }; beforeEach(() => { @@ -537,6 +538,7 @@ it('allows replacing the collectDependencies implementation', async () => { dynamicRequires: 'reject', inlineableCalls: ['_$$_IMPORT_DEFAULT', '_$$_IMPORT_ALL'], keepRequireNames: options.dev, + unstable_allowRequireContext: false, dependencyMapName: null, }, ); diff --git a/packages/metro-transform-worker/src/index.js b/packages/metro-transform-worker/src/index.js index 39138feccd..0aa5a3034f 100644 --- a/packages/metro-transform-worker/src/index.js +++ b/packages/metro-transform-worker/src/index.js @@ -99,6 +99,8 @@ export type JsTransformerConfig = $ReadOnly<{ unstable_disableModuleWrapping: boolean, unstable_disableNormalizePseudoGlobals: boolean, unstable_compactOutput: boolean, + /** Enable `require.context` statements which can be used to import multiple files in a directory. */ + unstable_allowRequireContext: boolean, }>; export type {CustomTransformOptions} from 'metro-babel-transformer'; @@ -396,6 +398,7 @@ async function transformJS( keepRequireNames: options.dev, allowOptionalDependencies: config.allowOptionalDependencies, dependencyMapName: config.unstable_dependencyMapReservedName, + unstable_allowRequireContext: config.unstable_allowRequireContext, }; // $FlowFixMe[unsupported-syntax] dynamic require const collectDependencies: CollectDependenciesFn = require(config.unstable_collectDependenciesPath); diff --git a/packages/metro/src/DeltaBundler/types.flow.js b/packages/metro/src/DeltaBundler/types.flow.js index ac7dbf4b43..30b467ab65 100644 --- a/packages/metro/src/DeltaBundler/types.flow.js +++ b/packages/metro/src/DeltaBundler/types.flow.js @@ -11,6 +11,7 @@ 'use strict'; import type {PrivateState} from './graphOperations'; +import type {RequireContextParams} from '../ModuleGraph/worker/collectDependencies'; import type {JsTransformOptions} from 'metro-transform-worker'; export type MixedOutput = { @@ -48,6 +49,9 @@ export type TransformResultDependency = { +isOptional?: boolean, +locs: $ReadOnlyArray, + + /** Context for requiring a collection of modules. */ + +contextParams?: RequireContextParams, }, }; diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index 41416c9969..4c72df8315 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -40,8 +40,711 @@ const opts = { keepRequireNames: true, allowOptionalDependencies: false, dependencyMapName: null, + unstable_allowRequireContext: false, }; +describe(`require.context`, () => { + const optsWithoutContext = {...opts, unstable_allowRequireContext: false}; + const optsWithContext = {...opts, unstable_allowRequireContext: true}; + + it('does not extract/transform if feature is disabled', () => { + // TODO: Should this error/warn? + const ast = astFromCode(` + require.context('./', false, /foobar/m, 'eager'); + `); + const {dependencies} = collectDependencies(ast, optsWithoutContext); + expect(dependencies).toEqual([]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + require.context('./', false, /foobar/m, 'eager'); + `), + ); + }); + + it('can omit 2nd-4th arguments', () => { + const ast = astFromCode(` + const a = require.context('./'); + const b = require.context('./', false); + const c = require.context('./', true, /custom/i); + const d = require.context('./', true, /.*/, 'eager') + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: false, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'custom', + flags: 'i', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'eager', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const c = require(${dependencyMapName}[2], "./"); + const d = require(${dependencyMapName}[3], "./"); + `), + ); + }); + + it('can pass undefined for 2nd-4th arguments', () => { + const ast = astFromCode(` + const a = require.context('./', undefined, undefined, undefined); + const b = require.context('./', false, undefined, undefined); + const c = require.context('./', undefined, /custom/i, undefined); + const d = require.context('./', undefined, undefined, 'eager'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: false, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'custom', + flags: 'i', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'eager', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const c = require(${dependencyMapName}[2], "./"); + const d = require(${dependencyMapName}[3], "./"); + `), + ); + }); + + it('can understand constant assignments', () => { + const ast = astFromCode(` + const DOT_SLASH_FOO = './foo'; + const FALSE = false; + const EAGER = 'eager'; + const a = require.context(DOT_SLASH_FOO, FALSE, /pattern/, EAGER); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './foo', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'pattern', + flags: '', + }, + mode: 'eager', + recursive: false, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const DOT_SLASH_FOO = './foo'; + const FALSE = false; + const EAGER = 'eager'; + const a = require(${dependencyMapName}[0], "./foo"); + `), + ); + }); + + it.skip('can understand regex constant assignments', () => { + // TODO: augment Babel's path.evaluate() with regex support + const ast = astFromCode(` + const DOT_SLASH_FOO = './foo'; + const FALSE = false; + const EAGER = 'eager'; + const PATTERN = /pattern/; + const a = require.context(DOT_SLASH_FOO, FALSE, PATTERN, EAGER); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './foo', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'pattern', + flags: '', + }, + mode: 'eager', + recursive: false, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const DOT_SLASH_FOO = "./foo"; + const FALSE = false; + const EAGER = "eager"; + const PATTERN = /pattern/; + const a = require(${dependencyMapName}[0], "./foo"); + `), + ); + }); + + it('distinguishes require from require.context', () => { + const ast = astFromCode(` + const a = require.context('./'); + const anotherA = require.context('./'); + const b = require('./'); + const anotherB = require('./'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: expect.not.objectContaining({ + contextParams: expect.anything(), + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const anotherA = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes require.context based on path', () => { + const ast = astFromCode(` + const a = require.context('./a/'); + const anotherA = require.context('./a/'); + const b = require.context('./b/'); + const anotherB = require.context('./b/'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './a/', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './b/', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./a/"); + const anotherA = require(${dependencyMapName}[0], "./a/"); + const b = require(${dependencyMapName}[1], "./b/"); + const anotherB = require(${dependencyMapName}[1], "./b/"); + `), + ); + }); + + it('distinguishes require.context based on trailing slash in path', () => { + // TODO: Can/should we merge these two? + const ast = astFromCode(` + const a = require.context('.'); + const anotherA = require.context('.'); + const b = require.context('./'); + const anotherB = require.context('./'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: '.', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "."); + const anotherA = require(${dependencyMapName}[0], "."); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes between backslash and slash in path', () => { + // TODO: Can/should we merge these two? + const ast = astFromCode(` + const a = require.context('.\\\\'); + const anotherA = require.context('.\\\\'); + const b = require.context('./'); + const anotherB = require.context('./'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: '.\\', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], ".\\\\"); + const anotherA = require(${dependencyMapName}[0], ".\\\\"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes require.context based on `recursive`', () => { + const ast = astFromCode(` + const a = require.context('./', true); + const anotherA = require.context('./'); + const b = require.context('./', false); + const anotherB = require.context('./', false); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: false, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const anotherA = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes require.context based on filter pattern', () => { + const ast = astFromCode(` + const a = require.context('./', true, /foo/); + const anotherA = require.context('./', true, /foo/); + const b = require.context('./', true, /.*/); + const anotherB = require.context('./', true); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'foo', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const anotherA = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes require.context based on filter flags', () => { + const ast = astFromCode(` + const a = require.context('./', true, /foo/m); + const anotherA = require.context('./', true, /foo/m); + const b = require.context('./', true, /foo/); + const anotherB = require.context('./', true, /foo/); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'foo', + flags: 'm', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'foo', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const anotherA = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes require.context based on mode', () => { + const ast = astFromCode(` + const a = require.context('./', true, /.*/, 'sync'); + const anotherA = require.context('./', true, /.*/); + const b = require.context('./', true, /.*/, 'eager'); + const anotherB = require.context('./', true, /.*/, 'eager'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'eager', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const anotherA = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it(`asserts invalid first argument`, () => { + const ast = astFromCode(` + const a = require.context(42); +`); + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: 42 + First argument of \`require.context\` should be a string denoting the directory to require." + `); + }); + it(`asserts invalid second argument`, () => { + const ast = astFromCode(` + const a = require.context('./dir', 'hey'); +`); + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: 'hey' + Second argument of \`require.context\` should be an optional boolean indicating if files should be imported recursively or not." + `); + }); + it(`asserts invalid third argument`, () => { + const ast = astFromCode(` + const a = require.context('./dir', false, new RegExp('foobar')); +`); + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: new RegExp('foobar') + Third argument of \`require.context\` should be an optional RegExp pattern matching all of the files to import, instead found node of type: NewExpression." + `); + }); + it(`asserts invalid fourth argument`, () => { + const ast = astFromCode(` + const a = require.context('./dir', false, /foobar/, 34); +`); + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: 34 + Fourth argument of \`require.context\` should be an optional string \\"mode\\" denoting how the modules will be resolved." + `); + }); + it(`asserts invalid fourth argument enum value`, () => { + const ast = astFromCode(` + const a = require.context('./dir', false, /foobar/, 'hello'); +`); + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: 'hello' + require.context \\"hello\\" mode is not supported. Expected one of: sync, eager, lazy, lazy-once" + `); + }); + it(`asserts too many arguments`, () => { + const ast = astFromCode(` + const a = require.context('./dir', false, /foobar/, 'sync', 'hey'); +`); + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: require.context('./dir', false, /foobar/, 'sync', 'hey') + Too many arguments provided to \`require.context\` call. Expected 4, got: 5" + `); + }); + it(`asserts no arguments`, () => { + const ast = astFromCode(` + const a = require.context(); +`); + expect(() => + collectDependencies(ast, optsWithContext), + ).toThrowErrorMatchingInlineSnapshot( + `"Invalid call at line 2: require.context()"`, + ); + }); +}); + it('collects unique dependency identifiers and transforms the AST', () => { const ast = astFromCode(` const a = require('b/lib/a'); @@ -319,6 +1022,7 @@ describe('Evaluating static arguments', () => { keepRequireNames: true, allowOptionalDependencies: false, dependencyMapName: null, + unstable_allowRequireContext: false, }; const {dependencies} = collectDependencies(ast, opts); expect(dependencies).toEqual([]); @@ -480,6 +1184,7 @@ describe('optional dependencies', () => { keepRequireNames: true, allowOptionalDependencies: true, dependencyMapName: null, + unstable_allowRequireContext: false, }; const validateDependencies = (dependencies, expectedCount) => { let hasAsync = false; diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index f0b9897815..d302a25cbf 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -37,6 +37,20 @@ export type Dependency = $ReadOnly<{ name: string, }>; +// TODO: Convert to a Flow enum +type ContextMode = 'sync' | 'eager' | 'lazy' | 'lazy-once'; + +type ContextFilter = {pattern: string, flags: string}; + +export type RequireContextParams = $ReadOnly<{ + /* Should search for files recursively. Optional, default `true` when `require.context` is used */ + recursive: boolean, + /* Filename filter pattern for use in `require.context`. Optional, default `.*` (any file) when `require.context` is used */ + filter: $ReadOnly, + /** Mode for resolving dynamic dependencies. Defaults to `sync` */ + mode: ContextMode, +}>; + type DependencyData = $ReadOnly<{ // If null, then the dependency is synchronous. // (ex. `require('foo')`) @@ -45,6 +59,8 @@ type DependencyData = $ReadOnly<{ // If left unspecified, then the dependency is unconditionally split. splitCondition?: TSplitCondition, locs: Array, + /** Context for requiring a collection of modules. */ + contextParams?: RequireContextParams, }>; export type MutableInternalDependency = { @@ -66,6 +82,8 @@ export type State = { dependencyMapIdentifier: ?Identifier, keepRequireNames: boolean, allowOptionalDependencies: AllowOptionalDependencies, + /** Enable `require.context` statements which can be used to import multiple files in a directory. */ + unstable_allowRequireContext: boolean, }; export type Options = $ReadOnly<{ @@ -77,6 +95,8 @@ export type Options = $ReadOnly<{ allowOptionalDependencies: AllowOptionalDependencies, dependencyRegistry?: ModuleDependencyRegistry, dependencyTransformer?: DependencyTransformer, + /** Enable `require.context` statements which can be used to import multiple files in a directory. */ + unstable_allowRequireContext: boolean, }>; export type CollectedDependencies<+TSplitCondition> = $ReadOnly<{ @@ -87,8 +107,8 @@ export type CollectedDependencies<+TSplitCondition> = $ReadOnly<{ // Registry for the dependency of a module. // Defines when dependencies should be collapsed. -// E.g. should a module that's once required optinally and once not -// be tretaed as the smae or different dependencies. +// E.g. should a module that's once required optionally and once not +// be treated as the same or different dependencies. export interface ModuleDependencyRegistry<+TSplitCondition> { registerDependency( qualifier: ImportQualifier, @@ -151,6 +171,7 @@ function collectDependencies( dynamicRequires: options.dynamicRequires, keepRequireNames: options.keepRequireNames, allowOptionalDependencies: options.allowOptionalDependencies, + unstable_allowRequireContext: options.unstable_allowRequireContext, }; const visitor = { @@ -199,6 +220,26 @@ function collectDependencies( return; } + // Match `require.context` + if ( + // Feature gate, defaults to `false`. + state.unstable_allowRequireContext && + callee.type === 'MemberExpression' && + // `require` + callee.object.type === 'Identifier' && + callee.object.name === 'require' && + // `context` + callee.property.type === 'Identifier' && + callee.property.name === 'context' && + !callee.computed && + // Ensure `require` refers to the global and not something else. + !path.scope.getBinding('require') + ) { + processRequireContextCall(path, state); + visited.add(path.node); + return; + } + if ( name != null && state.dependencyCalls.has(name) && @@ -251,6 +292,132 @@ function collectDependencies( }; } +/** Extract args passed to the `require.context` method. */ +function getRequireContextArgs( + path: NodePath, +): [string, RequireContextParams] { + const args = path.get('arguments'); + + let directory: string; + if (!Array.isArray(args) || args.length < 1) { + throw new InvalidRequireCallError(path); + } else { + const result = args[0].evaluate(); + if (result.confident && typeof result.value === 'string') { + directory = result.value; + } else { + throw new InvalidRequireCallError( + result.deopt ?? args[0], + 'First argument of `require.context` should be a string denoting the directory to require.', + ); + } + } + + // Default to requiring through all directories. + let recursive: boolean = true; + if (args.length > 1) { + const result = args[1].evaluate(); + if (result.confident && typeof result.value === 'boolean') { + recursive = result.value; + } else if (!(result.confident && typeof result.value === 'undefined')) { + throw new InvalidRequireCallError( + result.deopt ?? args[1], + 'Second argument of `require.context` should be an optional boolean indicating if files should be imported recursively or not.', + ); + } + } + + // Default to all files. + let filter: ContextFilter = {pattern: '.*', flags: ''}; + if (args.length > 2) { + // evaluate() to check for undefined (because it's technically a scope lookup) + // but check the AST for the regex literal, since evaluate() doesn't do regex. + const result = args[2].evaluate(); + const argNode = args[2].node; + if (argNode.type === 'RegExpLiteral') { + // TODO: Handle `new RegExp(...)` -- `argNode.type === 'NewExpression'` + filter = { + pattern: argNode.pattern, + flags: argNode.flags || '', + }; + } else if (!(result.confident && typeof result.value === 'undefined')) { + throw new InvalidRequireCallError( + args[2], + `Third argument of \`require.context\` should be an optional RegExp pattern matching all of the files to import, instead found node of type: ${argNode.type}.`, + ); + } + } + + // Default to `sync`. + let mode: ContextMode = 'sync'; + if (args.length > 3) { + const result = args[3].evaluate(); + if (result.confident && typeof result.value === 'string') { + mode = getContextMode(args[3], result.value); + } else if (!(result.confident && typeof result.value === 'undefined')) { + throw new InvalidRequireCallError( + result.deopt ?? args[3], + 'Fourth argument of `require.context` should be an optional string "mode" denoting how the modules will be resolved.', + ); + } + } + + if (args.length > 4) { + throw new InvalidRequireCallError( + path, + `Too many arguments provided to \`require.context\` call. Expected 4, got: ${args.length}`, + ); + } + + return [ + directory, + { + recursive, + filter, + mode, + }, + ]; +} + +function getContextMode(path: NodePath, mode: string): ContextMode { + if ( + mode === 'sync' || + mode === 'eager' || + mode === 'lazy' || + mode === 'lazy-once' + ) { + return mode; + } + throw new InvalidRequireCallError( + path, + `require.context "${mode}" mode is not supported. Expected one of: sync, eager, lazy, lazy-once`, + ); +} + +function processRequireContextCall( + path: NodePath, + state: State, +): void { + const [directory, contextParams] = getRequireContextArgs(path); + const transformer = state.dependencyTransformer; + const dep = registerDependency( + state, + { + // We basically want to "import" every file in a folder and then filter them out with the given `filter` RegExp. + name: directory, + // Capture the matching context + contextParams, + asyncType: null, + optional: isOptionalDependency(directory, path, state), + }, + path, + ); + + // require() the generated module representing this context + path.get('callee').replaceWith(types.identifier('require')); + transformer.transformSyncRequire(path, dep, state); +} + function collectImports( path: NodePath<>, state: State, @@ -344,6 +511,7 @@ export type ImportQualifier = $ReadOnly<{ asyncType: AsyncDependencyType | null, splitCondition?: NodePath<>, optional: boolean, + contextParams?: RequireContextParams, }>; function registerDependency( @@ -352,7 +520,6 @@ function registerDependency( path: NodePath<>, ): InternalDependency { const dependency = state.dependencyRegistry.registerDependency(qualifier); - const loc = getNearestLocFromPath(path); if (loc != null) { dependency.locs.push(loc); @@ -419,14 +586,20 @@ function getModuleNameFromCallArgs(path: NodePath): ?string { return null; } + collectDependencies.getModuleNameFromCallArgs = getModuleNameFromCallArgs; class InvalidRequireCallError extends Error { - constructor({node}: any) { + constructor({node}: any, message?: string) { const line = node.loc && node.loc.start && node.loc.start.line; super( - `Invalid call at line ${line || ''}: ${generate(node).code}`, + [ + `Invalid call at line ${line || ''}: ${generate(node).code}`, + message, + ] + .filter(Boolean) + .join('\n'), ); } } @@ -469,9 +642,11 @@ const DefaultDependencyTransformer: DependencyTransformer = { state: State, ): void { const moduleIDExpression = createModuleIDExpression(dependency, state); - path.node.arguments = state.keepRequireNames - ? [moduleIDExpression, types.stringLiteral(dependency.name)] - : [moduleIDExpression]; + path.node.arguments = [moduleIDExpression]; + // Always add the debug name argument last + if (state.keepRequireNames) { + path.node.arguments.push(types.stringLiteral(dependency.name)); + } }, transformImportCall( @@ -546,6 +721,44 @@ function createModuleNameLiteral(dependency: InternalDependency) { return types.stringLiteral(dependency.name); } +/** + * Given an import qualifier, return a key used to register the dependency. + * Generally this return the `ImportQualifier.name` property, but in the case + * of `require.context` more attributes can be appended to distinguish various combinations that would otherwise conflict. + * + * For example, the following case would have collision issues if they all utilized the `name` property: + * ``` + * require('./foo'); + * require.context('./foo'); + * require.context('./foo', true, /something/); + * require.context('./foo', false, /something/); + * require.context('./foo', false, /something/, 'lazy'); + * ``` + * + * This method should be utilized by `registerDependency`. + */ +function getKeyForDependency(qualifier: ImportQualifier): string { + let key = qualifier.name; + + const {contextParams} = qualifier; + // Add extra qualifiers when using `require.context` to prevent collisions. + if (contextParams) { + // NOTE(EvanBacon): Keep this synchronized with `RequireContextParams`, if any other properties are added + // then this key algorithm should be updated to account for those properties. + // Example: `./directory__true__/foobar/m__lazy` + key += [ + '', + 'context', + String(contextParams.recursive), + String(contextParams.filter.pattern), + String(contextParams.filter.flags), + contextParams.mode, + // Join together and append to the name: + ].join('__'); + } + return key; +} + class DefaultModuleDependencyRegistry implements ModuleDependencyRegistry { @@ -554,8 +767,9 @@ class DefaultModuleDependencyRegistry registerDependency( qualifier: ImportQualifier, ): InternalDependency { + const key = getKeyForDependency(qualifier); let dependency: ?InternalDependency = - this._dependencies.get(qualifier.name); + this._dependencies.get(key); if (dependency == null) { const newDependency: MutableInternalDependency = { @@ -568,14 +782,17 @@ class DefaultModuleDependencyRegistry if (qualifier.optional) { newDependency.isOptional = true; } + if (qualifier.contextParams) { + newDependency.contextParams = qualifier.contextParams; + } dependency = newDependency; - this._dependencies.set(qualifier.name, dependency); + this._dependencies.set(key, dependency); } else { const original = dependency; dependency = collapseDependencies(original, qualifier); if (original !== dependency) { - this._dependencies.set(qualifier.name, dependency); + this._dependencies.set(key, dependency); } }