diff --git a/docs/API.md b/docs/API.md index 4276d324fd..13f1a08709 100644 --- a/docs/API.md +++ b/docs/API.md @@ -91,6 +91,7 @@ Builds a single bundle for `entry`, like [`metro build`](./CLI.md#build-entry). - `entry` (string): **Required.** The [entry point](./Concepts.md#entry-point) file to bundle. - `platform` (string): The [platform](./Concepts.md#platform) to bundle for (e.g. `'web'`, `'android'`, `'ios'`). Defaults to `'web'`. +- `environment` (string): The environment to bundle for (e.g. `'react-server'`), equivalent to the bundle URL parameter [`environment`](./GettingStarted.md#bundle). Unset, empty or `'client'` for the default (client) environment. - `dev` (boolean): Build a development bundle, in which `__DEV__` is `true`. Otherwise, `__DEV__` and `process.env.NODE_ENV` are inlined as `false` and `'production'`. Defaults to `false`. - `minify` (boolean): Whether to minify the bundle. Defaults to `true`. - `out` (string): Path for the bundle (with `.js` added if missing) and source map (with `.map` extension). Override either path with `bundleOut` or `sourceMapOut`. For example, `out: 'dist/main'` or `out: 'dist/main.js'` with `sourceMap: true` writes `dist/main.js` and `dist/main.map`. diff --git a/docs/GettingStarted.md b/docs/GettingStarted.md index ce5d739a0b..8321a30f9c 100644 --- a/docs/GettingStarted.md +++ b/docs/GettingStarted.md @@ -178,10 +178,11 @@ Metro can also serve a variant of an asset for a specific [platform](./Concepts. Any JS file in the [project root](./Concepts.md#project-root-and-watch-folders) can be the [entry point](./Concepts.md#entry-point) of a bundle, which includes the file and, recursively, everything it requires. To request a bundle, use the file's path relative to the project root (or [`server.unstable_serverRoot`](./Configuration.md#unstable_serverroot-experimental), if set), with `.js` changed to `.bundle`. -Pass build options as query parameters. All are optional. Boolean ones take `true` or `false` and default to `false` unless noted. `dev`, `platform` and `minify` correspond to the bundle's settings of the same name. +Pass build options as query parameters. All are optional. Boolean ones take `true` or `false` and default to `false` unless noted. `dev`, `platform`, `environment` and `minify` correspond to the bundle's settings of the same name. - `dev`: Build in development mode. Defaults to `true`. - `platform`: The [platform](./Concepts.md#platform) requesting the bundle (e.g. `ios`). Defaults to the platform suffix of the requested file name, if any (e.g. `ios` for `index.ios.bundle`). +- `environment`: The environment to bundle for (e.g. `react-server`), passed to the transformer as `options.environment`, to Babel plugins as `caller.environment` by Metro's Babel transformer, and to the resolver as [`context.environment`](./Resolution.md#environment-string). Unset, empty or `client` for the default (client) environment. - `minify`: Minify the code. - `excludeSource`: Leave the source code out of the source map, e.g. `/index.map?platform=ios&dev=true&excludeSource=true` returns a source map without `sourcesContent`. - `inlineSourceMap`: Append the source map to the bundle as a base64 `data:` URL. @@ -209,7 +210,7 @@ Required. Transforms a module's code. It receives an object with: - `filename`: The path of the file, relative to the project root. - `src`: The source code. -- `options`: Options for this transformation, e.g. `dev`, `platform`, `minify`, `projectRoot`, `customTransformOptions` and `unstable_transformProfile`. +- `options`: Options for this transformation, e.g. `dev`, `platform`, `minify`, `projectRoot`, `customTransformOptions`, `unstable_transformProfile` and `environment`. - `plugins`: Babel plugins that Metro wants applied to the code. It must return an object with an `ast` key containing the Babel AST of the transformed code, and optionally Babel `metadata`. Metro gets function names for stack traces from `metadata`, so apply the `plugins` it passes in and return the resulting `metadata` to keep them. For example, using Babel: diff --git a/docs/Resolution.md b/docs/Resolution.md index 2d399f9b7d..e3c66f079c 100644 --- a/docs/Resolution.md +++ b/docs/Resolution.md @@ -230,6 +230,10 @@ The set of file extensions used to identify asset files. Defaults to [`resolver. `true` for a development bundle, `false` otherwise. +#### `environment: ?string` + +The environment to bundle for (e.g. `'react-server'`), from the [`environment`](./GettingStarted.md#bundle) bundle option. Absent for the default environment. + #### `fileSystemLookup: string => {exists: true, type: 'f'|'d', realPath: string} | {exists: false}` _Added in v0.81.0_ @@ -397,7 +401,7 @@ Metro caches and reuses resolver results, which matters mainly for [custom resol 1. For given origin module paths _A_ and _B_ and target module name _M_, the resolution for _M_ may be reused if **all** of the following conditions hold: 1. _A_ and _B_ are in the same directory. - 2. The contents of [`dev`](#dev-boolean) and [`customResolverOptions`](#customresolveroptions-string-mixed) are equivalent ( = serialize to JSON the same) in both calls to the resolver. + 2. The contents of [`dev`](#dev-boolean), [`customResolverOptions`](#customresolveroptions-string-mixed) and [`environment`](#environment-string) are equivalent ( = serialize to JSON the same) in both calls to the resolver. 3. The `platform` is the same in both calls. 4. [`isESMImport`](#isesmimport-boolean) is the same in both calls. 2. Any cache of resolutions must be invalidated if any file in the project has changed. diff --git a/packages/metro-babel-transformer/src/__tests__/transform-test.js b/packages/metro-babel-transformer/src/__tests__/transform-test.js index 7ef080ae11..4a91a38dbe 100644 --- a/packages/metro-babel-transformer/src/__tests__/transform-test.js +++ b/packages/metro-babel-transformer/src/__tests__/transform-test.js @@ -87,18 +87,19 @@ test('exposes the Babel runtime module name and version to presets via the calle }); }); -test('omits the Babel runtime from the caller when not provided', () => { +test('omits the Babel runtime and environment from the caller when not provided', () => { let callerKeys; transform({ filename: 'foo.js', src: 'console.log("foo");', plugins: [ babel => { - callerKeys = ['babelRuntimeModuleName', 'enableBabelRuntime'].filter( - key => - babel.caller( - caller => caller != null && Object.hasOwn(caller, key), - ), + callerKeys = [ + 'babelRuntimeModuleName', + 'enableBabelRuntime', + 'environment', + ].filter(key => + babel.caller(caller => caller != null && Object.hasOwn(caller, key)), ); return {visitor: {}}; }, @@ -151,3 +152,35 @@ test.each([ expect(callerValue).toBe(expected); }, ); + +test.each([ + ['react-server', 'react-server'], + [null, undefined], +])( + 'with environment: %s, exposes it on the caller: %s', + (environment, expected) => { + let callerValue; + transform({ + filename: 'foo.js', + src: 'console.log("foo");', + plugins: [ + babel => { + callerValue = babel.caller(caller => caller?.environment); + return {visitor: {}}; + }, + ], + options: { + dev: true, + enableBabelRuntime: false, + enableBabelRCLookup: false, + environment, + globalPrefix: '__metro__', + minify: false, + platform: null, + publicPath: 'test', + projectRoot: PROJECT_ROOT, + }, + }); + expect(callerValue).toBe(expected); + }, +); diff --git a/packages/metro-babel-transformer/src/index.js b/packages/metro-babel-transformer/src/index.js index 275143304e..ce4566a11e 100644 --- a/packages/metro-babel-transformer/src/index.js +++ b/packages/metro-babel-transformer/src/index.js @@ -39,6 +39,7 @@ type BabelTransformerOptions = Readonly<{ dev: boolean, enableBabelRCLookup?: boolean, enableBabelRuntime: boolean | string, + environment?: ?string, extendsBabelConfigPath?: string, experimentalImportSupport?: boolean, hermesParser?: boolean, @@ -101,6 +102,11 @@ function transform( ? 'development' : process.env.BABEL_ENV || 'production'; + // Omitted when unset, so builds without an environment get the same caller. + // Typed separately to avoid spreading a second union into the caller. + const environmentCaller: {environment?: string} = + options.environment != null ? {environment: options.environment} : {}; + try { const babelConfig: BabelTransformOptions = { ast: true, @@ -122,6 +128,7 @@ function transform( : null), // Whether `metro:inline` specifiers will resolve. supportsInlineModules: options.supportsInlineModules, + ...environmentCaller, }, // NOTE(EvanBacon): We split the parse/transform steps up to accommodate // Hermes parsing, but this defaults to cloning the AST which increases diff --git a/packages/metro-resolver/API.md b/packages/metro-resolver/API.md index 11327cd2f1..5fb9d762a9 100644 --- a/packages/metro-resolver/API.md +++ b/packages/metro-resolver/API.md @@ -65,6 +65,7 @@ export type ResolutionContext = Readonly<{ disableHierarchicalLookup: boolean; extraNodeModules: null | undefined | {[packageName: string]: string}; dev: boolean; + environment?: null | undefined | string; getPackage: (packageJsonPath: string) => null | undefined | PackageJson; getPackageForModule: (absoluteModulePath: string) => null | undefined | PackageForModule; dependency?: TransformResultDependency | undefined; diff --git a/packages/metro-resolver/src/types.js b/packages/metro-resolver/src/types.js index 8a877ac20a..b82e3f505f 100644 --- a/packages/metro-resolver/src/types.js +++ b/packages/metro-resolver/src/types.js @@ -158,6 +158,12 @@ export type ResolutionContext = Readonly<{ /** Is resolving for a development bundle. */ dev: boolean, + /** + * The environment to bundle for, e.g. `'react-server'`. Absent for the + * default environment. + */ + environment?: ?string, + /** * Get the parsed contents of the specified `package.json` file. */ diff --git a/packages/metro-transform-worker/API.md b/packages/metro-transform-worker/API.md index ce03bd0d60..94d17ea5f7 100644 --- a/packages/metro-transform-worker/API.md +++ b/packages/metro-transform-worker/API.md @@ -52,6 +52,7 @@ export type JsTransformerConfig = Readonly<{ export type JsTransformOptions = Readonly<{ customTransformOptions?: CustomTransformOptions | undefined; dev: boolean; + environment?: null | undefined | string; experimentalImportSupport?: boolean | undefined; inlinePlatform: boolean; inlineRequires: boolean; diff --git a/packages/metro-transform-worker/src/index.js b/packages/metro-transform-worker/src/index.js index 0906b0b78f..26817861b2 100644 --- a/packages/metro-transform-worker/src/index.js +++ b/packages/metro-transform-worker/src/index.js @@ -134,6 +134,7 @@ export type {CustomTransformOptions} from 'metro-babel-transformer'; export type JsTransformOptions = Readonly<{ customTransformOptions?: CustomTransformOptions, dev: boolean, + environment?: ?string, experimentalImportSupport?: boolean, inlinePlatform: boolean, inlineRequires: boolean, diff --git a/packages/metro/API.md b/packages/metro/API.md index 6a0ea41949..bed436cc0b 100644 --- a/packages/metro/API.md +++ b/packages/metro/API.md @@ -224,6 +224,7 @@ export type RunBuildOptions = { entry: string; assets?: boolean | undefined; dev?: boolean | undefined; + environment?: string | undefined; out?: string | undefined; bundleOut?: string | undefined; sourceMapOut?: string | undefined; diff --git a/packages/metro/src/DeltaBundler/Transformer.js b/packages/metro/src/DeltaBundler/Transformer.js index ae10b23d2e..43050addcd 100644 --- a/packages/metro/src/DeltaBundler/Transformer.js +++ b/packages/metro/src/DeltaBundler/Transformer.js @@ -193,6 +193,7 @@ export default class Transformer { const { customTransformOptions, dev, + environment, experimentalImportSupport, inlinePlatform, inlineRequires, @@ -253,6 +254,9 @@ export default class Transformer { unstable_memoizeInlineRequires, unstable_nonMemoizedInlineRequires, unstable_transformProfile, + // Omitted when unset, keeping keys stable for builds without an + // environment. + ...(environment != null ? [environment] : []), ]); let sha1: string; diff --git a/packages/metro/src/DeltaBundler/__tests__/Transformer-test.js b/packages/metro/src/DeltaBundler/__tests__/Transformer-test.js index 3f613d987c..d3030f7cb4 100644 --- a/packages/metro/src/DeltaBundler/__tests__/Transformer-test.js +++ b/packages/metro/src/DeltaBundler/__tests__/Transformer-test.js @@ -737,4 +737,44 @@ describe('Transformer', function () { expect(transform).toHaveBeenCalledTimes(2); }); }); + + test('adds the environment to the cache key only when set', async () => { + const get = jest.fn(); + const transformerInstance = new Transformer( + { + ...commonOptions, + cacheStores: [{get, set: jest.fn()}], + // Read the cache for every transform, including repeated keys. + transformer: { + ...commonOptions.transformer, + unstable_shareTransformResults: false, + }, + watchFolders, + }, + {getOrComputeSha1}, + ); + require('../WorkerFarm').default.prototype.transform.mockReturnValue({ + sha1: '0123456789012345678901234567890123456789', + result: {}, + }); + for (const transformOptions of [ + {}, + {environment: null}, + {environment: 'react-server'}, + ]) { + await transformerInstance.transformFile( + path.join(projectRoot, 'foo.js'), + transformOptions, + ); + } + // Each key is the partial key followed by the file's SHA-1. + const [unset, nullEnvironment, server] = get.mock.calls.map(([key]) => + key.toString('hex').slice(0, 32), + ); + // Pinned, so that existing transform caches stay valid for builds without + // an environment. + expect(unset).toBe('f1c5c1a8c7f20b582f90f6cc8088ba2e'); + expect(nullEnvironment).toBe(unset); + expect(server).not.toBe(unset); + }); }); diff --git a/packages/metro/src/index.flow.js b/packages/metro/src/index.flow.js index 07018b9188..1d5d0d6b8d 100644 --- a/packages/metro/src/index.flow.js +++ b/packages/metro/src/index.flow.js @@ -113,6 +113,7 @@ export type RunBuildOptions = { entry: string, assets?: boolean, dev?: boolean, + environment?: string, out?: string, bundleOut?: string, sourceMapOut?: string, @@ -440,6 +441,7 @@ export const runBuild = async ( customTransformOptions = DEFAULTS.customTransformOptions, dev = false, entry, + environment, onBegin, onComplete, onProgress, @@ -461,6 +463,7 @@ export const runBuild = async ( const requestOptions = { dev, entryFile: entry, + environment, inlineSourceMap: sourceMap && !sourceMapUrl, minify, platform, diff --git a/packages/metro/src/integration_tests/__tests__/environment-test.js b/packages/metro/src/integration_tests/__tests__/environment-test.js new file mode 100644 index 0000000000..538af63b54 --- /dev/null +++ b/packages/metro/src/integration_tests/__tests__/environment-test.js @@ -0,0 +1,94 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +'use strict'; + +import type {CustomResolutionContext} from 'metro-resolver'; + +const Metro = require('../../..'); +const execBundle = require('../execBundle'); +const path = require('node:path'); + +jest.useRealTimers(); +jest.setTimeout(60 * 1000); + +async function getConfig() { + const baseConfig = await Metro.loadConfig({ + config: require.resolve('../metro.config.js'), + }); + const resolvedEnvironments = new Set(); + const config = { + ...baseConfig, + // Build with Metro's own Babel transformer, which leaves Babel to discover + // the fixture's `babel.config.js` from the project root. + projectRoot: path.resolve(__dirname, '../basic_bundle/environment'), + resolver: { + ...baseConfig.resolver, + resolveRequest: ( + context: CustomResolutionContext, + moduleName: string, + platform: string | null, + ) => { + resolvedEnvironments.add(context.environment); + return context.resolveRequest(context, moduleName, platform); + }, + }, + transformer: { + ...baseConfig.transformer, + babelTransformerPath: require.resolve('metro-babel-transformer'), + }, + }; + return {config, resolvedEnvironments}; +} + +test('one server builds the same entry with and without an environment', async () => { + const {config, resolvedEnvironments} = await getConfig(); + let onClose; + const closed = new Promise(resolve => (onClose = resolve)); + const {httpServer} = await Metro.runServer(config, {onClose}); + // Workaround for https://github.com/nodejs/node/issues/54484 + const fetchAndExec = async (pathname: string) => + execBundle( + await ( + await fetch( + 'http://localhost:' + httpServer.address().port + pathname, + { + headers: {Connection: 'close'}, + }, + ) + ).text(), + ); + try { + expect( + await fetchAndExec('/index.bundle?platform=ios&environment=react-server'), + ).toMatchObject({environment: 'react-server'}); + expect(resolvedEnvironments).toEqual(new Set(['react-server'])); + + resolvedEnvironments.clear(); + expect(await fetchAndExec('/index.bundle?platform=ios')).toMatchObject({ + environment: null, + }); + expect(resolvedEnvironments).toEqual(new Set([undefined])); + } finally { + httpServer.close(); + await closed; + } +}); + +test('runBuild passes the environment to the transformer and resolver', async () => { + const {config, resolvedEnvironments} = await getConfig(); + const {code} = await Metro.runBuild(config, { + entry: 'index.js', + environment: 'react-server', + }); + expect(execBundle(code)).toMatchObject({environment: 'react-server'}); + expect(resolvedEnvironments).toEqual(new Set(['react-server'])); +}); diff --git a/packages/metro/src/integration_tests/basic_bundle/environment/babel.config.js b/packages/metro/src/integration_tests/basic_bundle/environment/babel.config.js new file mode 100644 index 0000000000..2dd66210d0 --- /dev/null +++ b/packages/metro/src/integration_tests/basic_bundle/environment/babel.config.js @@ -0,0 +1,33 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * @oncall react_native + */ + +'use strict'; + +// A minimal stand-in for a plugin that reads the environment from Babel caller +// data. As a root config it applies to every file in the bundle, so it also +// strips Flow, from Metro's own polyfills. +module.exports = api => { + const environment = api.caller(caller => caller?.environment); + return { + plugins: [ + require.resolve('flow-parser/babel-plugin'), + require.resolve('@babel/plugin-transform-flow-strip-types'), + ({types}) => ({ + visitor: { + Identifier(path) { + if (path.node.name === 'ENVIRONMENT') { + path.replaceWith(types.valueToNode(environment ?? null)); + } + }, + }, + }), + ], + }; +}; diff --git a/packages/metro/src/integration_tests/basic_bundle/environment/index.js b/packages/metro/src/integration_tests/basic_bundle/environment/index.js new file mode 100644 index 0000000000..24e2f0b35d --- /dev/null +++ b/packages/metro/src/integration_tests/basic_bundle/environment/index.js @@ -0,0 +1,14 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * @oncall react_native + */ + +'use strict'; + +// Replaced by the fixture's Babel config. +export const environment = ENVIRONMENT; diff --git a/packages/metro/src/lib/__tests__/getGraphId-test.js b/packages/metro/src/lib/__tests__/getGraphId-test.js index 11e20f5008..3e36b008c2 100644 --- a/packages/metro/src/lib/__tests__/getGraphId-test.js +++ b/packages/metro/src/lib/__tests__/getGraphId-test.js @@ -270,6 +270,7 @@ describe('getGraphId', () => { customTransformOptions: undefined, experimentalImportSupport: false, dev: true, + environment: null, minify: true, type: 'module', platform: null, @@ -306,4 +307,25 @@ describe('getGraphId', () => { ), ); }); + + test('adds no environment key when the environment is unset', () => { + expect( + getGraphId( + '/root/waddup', + { + dev: true, + minify: true, + type: 'module', + platform: 'web', + unstable_transformProfile: 'default', + }, + { + shallow: false, + lazy: false, + unstable_allowRequireContext: false, + resolverOptions: {dev: true}, + }, + ), + ).not.toContain('environment'); + }); }); diff --git a/packages/metro/src/lib/__tests__/parseBundleOptionsFromBundleRequestUrl-test.js b/packages/metro/src/lib/__tests__/parseBundleOptionsFromBundleRequestUrl-test.js index 48d0d669ea..6bb1440240 100644 --- a/packages/metro/src/lib/__tests__/parseBundleOptionsFromBundleRequestUrl-test.js +++ b/packages/metro/src/lib/__tests__/parseBundleOptionsFromBundleRequestUrl-test.js @@ -141,4 +141,24 @@ describe('parseBundleOptionsFromBundleRequestUrl', () => { ).toMatchObject({[optionName]: false}); }); }); + + describe('environment', () => { + test('is retrieved from the url', () => { + expect( + parseBundleOptionsFromBundleRequestUrl( + 'http://localhost/my/bundle.bundle?environment=react-server', + new Set([]), + ), + ).toMatchObject({environment: 'react-server'}); + }); + + test.each([ + ['http://localhost/my/bundle.bundle'], + ['http://localhost/my/bundle.bundle?environment='], + ])('is unset when absent or empty: %s', url => { + expect( + parseBundleOptionsFromBundleRequestUrl(url, new Set([])).environment, + ).toBeUndefined(); + }); + }); }); diff --git a/packages/metro/src/lib/__tests__/splitBundleOptions-test.js b/packages/metro/src/lib/__tests__/splitBundleOptions-test.js new file mode 100644 index 0000000000..70c53c8bf7 --- /dev/null +++ b/packages/metro/src/lib/__tests__/splitBundleOptions-test.js @@ -0,0 +1,33 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +import Server from '../../Server'; +import splitBundleOptions from '../splitBundleOptions'; + +test.each([ + ['react-server', 'react-server'], + [undefined, undefined], + [null, undefined], + ['', undefined], + ['client', undefined], +])( + 'with environment: %p, resolves and transforms for: %p', + (environment, expected) => { + const {resolverOptions, transformOptions} = splitBundleOptions({ + ...Server.DEFAULT_BUNDLE_OPTIONS, + entryFile: 'index.js', + environment, + platform: null, + }); + expect(resolverOptions.environment).toBe(expected); + expect(transformOptions.environment).toBe(expected); + }, +); diff --git a/packages/metro/src/lib/getGraphId.js b/packages/metro/src/lib/getGraphId.js index 9ed3068e62..62ce2d2fa4 100644 --- a/packages/metro/src/lib/getGraphId.js +++ b/packages/metro/src/lib/getGraphId.js @@ -38,6 +38,7 @@ export default function getGraphId( customResolverOptions: resolverOptions.customResolverOptions ?? {}, customTransformOptions: options.customTransformOptions ?? null, dev: options.dev, + environment: options.environment ?? undefined, experimentalImportSupport: options.experimentalImportSupport || false, minify: options.minify, platform: options.platform != null ? options.platform : null, diff --git a/packages/metro/src/lib/parseBundleOptionsFromBundleRequestUrl.js b/packages/metro/src/lib/parseBundleOptionsFromBundleRequestUrl.js index 8e0612deb1..b6d871ee1b 100644 --- a/packages/metro/src/lib/parseBundleOptionsFromBundleRequestUrl.js +++ b/packages/metro/src/lib/parseBundleOptionsFromBundleRequestUrl.js @@ -132,6 +132,7 @@ export default function parseBundleOptionsFromBundleRequestUrl( dev: getBoolQueryParam(searchParams, 'dev', true), // Absolute and relative paths are converted to paths relative to root entryFile: filePathPosix, + environment: searchParams.get('environment') || undefined, excludeSource: getBoolQueryParam(searchParams, 'excludeSource', false), inlineSourceMap: getBoolQueryParam(searchParams, 'inlineSourceMap', false), lazy: getBoolQueryParam(searchParams, 'lazy', false), diff --git a/packages/metro/src/lib/splitBundleOptions.js b/packages/metro/src/lib/splitBundleOptions.js index 0b9ff1873c..fa2113976a 100644 --- a/packages/metro/src/lib/splitBundleOptions.js +++ b/packages/metro/src/lib/splitBundleOptions.js @@ -17,15 +17,24 @@ import type {BundleOptions, SplitBundleOptions} from '../shared/types'; export default function splitBundleOptions( options: BundleOptions, ): SplitBundleOptions { + // Unset, empty and 'client' all mean the default (client) environment. + const environment = + options.environment != null && + options.environment !== '' && + options.environment !== 'client' + ? options.environment + : undefined; return { entryFile: options.entryFile, resolverOptions: { customResolverOptions: options.customResolverOptions, dev: options.dev, + environment, }, transformOptions: { customTransformOptions: options.customTransformOptions, dev: options.dev, + environment, minify: options.minify, platform: options.platform, type: 'module', diff --git a/packages/metro/src/lib/transformHelpers.js b/packages/metro/src/lib/transformHelpers.js index 4f686ed0ec..eb9bfb4ac8 100644 --- a/packages/metro/src/lib/transformHelpers.js +++ b/packages/metro/src/lib/transformHelpers.js @@ -53,6 +53,7 @@ async function calcTransformerOptions( const baseOptions = { customTransformOptions: options.customTransformOptions, dev: options.dev, + environment: options.environment, inlinePlatform: true, inlineRequires: false, minify: options.minify, diff --git a/packages/metro/src/node-haste/DependencyGraph/ModuleResolution.js b/packages/metro/src/node-haste/DependencyGraph/ModuleResolution.js index 12e279d46b..6cb45e255c 100644 --- a/packages/metro/src/node-haste/DependencyGraph/ModuleResolution.js +++ b/packages/metro/src/node-haste/DependencyGraph/ModuleResolution.js @@ -150,6 +150,7 @@ export class ModuleResolver { dependency, dev: resolverOptions.dev, disableHierarchicalLookup, + environment: resolverOptions.environment, extraNodeModules, fileSystemLookup, getPackage, diff --git a/packages/metro/src/shared/types.js b/packages/metro/src/shared/types.js index 7d0254ab55..ab8f1ebb1a 100644 --- a/packages/metro/src/shared/types.js +++ b/packages/metro/src/shared/types.js @@ -50,6 +50,7 @@ export type BundleOptions = { customTransformOptions: CustomTransformOptions, dev: boolean, entryFile: string, + readonly environment?: ?string, readonly excludeSource: boolean, readonly inlineSourceMap: boolean, readonly lazy: boolean, @@ -73,6 +74,7 @@ export type BuildOptions = Readonly<{ export type ResolverInputOptions = Readonly<{ customResolverOptions?: CustomResolverOptions, dev: boolean, + environment?: ?string, }>; export type SerializerOptions = { @@ -155,6 +157,7 @@ export type RequestOptions = Readonly< onProgress?: (transformedFileCount: number, totalFileCount: number) => void, customResolverOptions?: CustomResolverOptions, customTransformOptions?: CustomTransformOptions, + environment?: string, unstable_transformProfile?: TransformProfile, }>, >;