Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
5 changes: 3 additions & 2 deletions docs/GettingStarted.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down
6 changes: 5 additions & 1 deletion docs/Resolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_
Expand Down Expand Up @@ -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.
Expand Down
45 changes: 39 additions & 6 deletions packages/metro-babel-transformer/src/__tests__/transform-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: {}};
},
Expand Down Expand Up @@ -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);
},
);
7 changes: 7 additions & 0 deletions packages/metro-babel-transformer/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ type BabelTransformerOptions = Readonly<{
dev: boolean,
enableBabelRCLookup?: boolean,
enableBabelRuntime: boolean | string,
environment?: ?string,
extendsBabelConfigPath?: string,
experimentalImportSupport?: boolean,
hermesParser?: boolean,
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions packages/metro-resolver/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions packages/metro-resolver/src/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
1 change: 1 addition & 0 deletions packages/metro-transform-worker/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions packages/metro-transform-worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions packages/metro/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 4 additions & 0 deletions packages/metro/src/DeltaBundler/Transformer.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ export default class Transformer {
const {
customTransformOptions,
dev,
environment,
experimentalImportSupport,
inlinePlatform,
inlineRequires,
Expand Down Expand Up @@ -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;
Expand Down
40 changes: 40 additions & 0 deletions packages/metro/src/DeltaBundler/__tests__/Transformer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
3 changes: 3 additions & 0 deletions packages/metro/src/index.flow.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export type RunBuildOptions = {
entry: string,
assets?: boolean,
dev?: boolean,
environment?: string,
out?: string,
bundleOut?: string,
sourceMapOut?: string,
Expand Down Expand Up @@ -440,6 +441,7 @@ export const runBuild = async (
customTransformOptions = DEFAULTS.customTransformOptions,
dev = false,
entry,
environment,
onBegin,
onComplete,
onProgress,
Expand All @@ -461,6 +463,7 @@ export const runBuild = async (
const requestOptions = {
dev,
entryFile: entry,
environment,
inlineSourceMap: sourceMap && !sourceMapUrl,
minify,
platform,
Expand Down
94 changes: 94 additions & 0 deletions packages/metro/src/integration_tests/__tests__/environment-test.js
Original file line number Diff line number Diff line change
@@ -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<?string>();
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']));
});
Loading
Loading