Skip to content

Commit 07532e1

Browse files
committed
Add environment bundle option
Frameworks that build React Server Components bundle one project for several environments, such as `react-server` and the client, which need different resolution and transforms. Today they encode the environment in `customTransformOptions` and `customResolverOptions`. That keeps caches apart, but Metro core can't see it, so it can't vary resolution or module IDs by environment. This adds `environment`, a first-class bundle option beside `platform`. An unset or empty environment, or one named `client`, is the default (client) environment. It is set by the `environment=` bundle URL parameter, which lazy split-bundle URLs inherit from their parent, by `runBuild`'s `environment` option, and by `BundleOptions.environment` for `Server.build`. `splitBundleOptions` puts it in both the resolver and the transform options, from which it reaches: - The transform cache key, which also keeps shared transform results apart, and the options custom transformers receive (`options.environment`). `Transformer.transformFile` accepts it as a known transform option. - The Babel caller, as `caller.environment`, when the default `metro-babel-transformer` is used. - The resolution cache key, and `ResolutionContext.environment` for custom resolvers. - Graph IDs, so each environment gets its own graph. Metro doesn't act on the value yet. Per-environment export conditions and an environment-aware module ID factory will build on it. **Compatibility** Every new field is optional, so existing code that builds `BundleOptions`, transform or resolver options, or a `ResolutionContext` is unaffected. With the environment unset, transform cache keys, resolution cache keys, graph IDs and the Babel caller are byte-identical to before: the transform key gains a trailing element, and `getGraphId` and the Babel caller gain a key, only when it is set. Tests pin the unset transform key and graph ID. `null` and `'client'` are treated as unset. Frameworks that encode the environment in custom options can set `environment` instead. Moving over changes their transform cache keys once. Changelog: [Feature] Add the `environment` bundle option (`environment=` in bundle URLs), passed to transformers as `options.environment`, to Babel as `caller.environment` and to custom resolvers as `context.environment`
1 parent 136bb79 commit 07532e1

25 files changed

Lines changed: 385 additions & 9 deletions

File tree

‎docs/API.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ Builds a single bundle for `entry`, like [`metro build`](./CLI.md#build-entry).
9191

9292
- `entry` (string): **Required.** The [entry point](./Concepts.md#entry-point) file to bundle.
9393
- `platform` (string): The [platform](./Concepts.md#platform) to bundle for (e.g. `'web'`, `'android'`, `'ios'`). Defaults to `'web'`.
94+
- `environment` (string): The environment to bundle for (e.g. `'react-server'`), equivalent to the bundle URL parameter [`environment`](./GettingStarted.md#bundle). Unset, or `'client'`, for the default (client) environment.
9495
- `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`.
9596
- `minify` (boolean): Whether to minify the bundle. Defaults to `true`.
9697
- `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`.

‎docs/GettingStarted.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,10 +178,11 @@ Metro can also serve a variant of an asset for a specific [platform](./Concepts.
178178

179179
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`.
180180

181-
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.
181+
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.
182182

183183
- `dev`: Build in development mode. Defaults to `true`.
184184
- `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`).
185+
- `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.
185186
- `minify`: Minify the code.
186187
- `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`.
187188
- `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:
209210

210211
- `filename`: The path of the file, relative to the project root.
211212
- `src`: The source code.
212-
- `options`: Options for this transformation, e.g. `dev`, `platform`, `minify`, `projectRoot`, `customTransformOptions` and `unstable_transformProfile`.
213+
- `options`: Options for this transformation, e.g. `dev`, `platform`, `minify`, `projectRoot`, `customTransformOptions`, `unstable_transformProfile` and `environment`.
213214
- `plugins`: Babel plugins that Metro wants applied to the code.
214215

215216
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:

‎docs/Resolution.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,10 @@ The set of file extensions used to identify asset files. Defaults to [`resolver.
230230

231231
`true` for a development bundle, `false` otherwise.
232232

233+
#### `environment: ?string`
234+
235+
The environment to bundle for (e.g. `'react-server'`), from the [`environment`](./GettingStarted.md#bundle) bundle option. Absent for the default environment.
236+
233237
#### `fileSystemLookup: string => {exists: true, type: 'f'|'d', realPath: string} | {exists: false}`
234238

235239
_Added in v0.81.0_
@@ -397,7 +401,7 @@ Metro caches and reuses resolver results, which matters mainly for [custom resol
397401

398402
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:
399403
1. _A_ and _B_ are in the same directory.
400-
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.
404+
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.
401405
3. The `platform` is the same in both calls.
402406
4. [`isESMImport`](#isesmimport-boolean) is the same in both calls.
403407
2. Any cache of resolutions must be invalidated if any file in the project has changed.

‎packages/metro-babel-transformer/src/__tests__/transform-test.js‎

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,18 +87,19 @@ test('exposes the Babel runtime module name and version to presets via the calle
8787
});
8888
});
8989

90-
test('omits the Babel runtime from the caller when not provided', () => {
90+
test('omits the Babel runtime and environment from the caller when not provided', () => {
9191
let callerKeys;
9292
transform({
9393
filename: 'foo.js',
9494
src: 'console.log("foo");',
9595
plugins: [
9696
babel => {
97-
callerKeys = ['babelRuntimeModuleName', 'enableBabelRuntime'].filter(
98-
key =>
99-
babel.caller(
100-
caller => caller != null && Object.hasOwn(caller, key),
101-
),
97+
callerKeys = [
98+
'babelRuntimeModuleName',
99+
'enableBabelRuntime',
100+
'environment',
101+
].filter(key =>
102+
babel.caller(caller => caller != null && Object.hasOwn(caller, key)),
102103
);
103104
return {visitor: {}};
104105
},
@@ -151,3 +152,36 @@ test.each([
151152
expect(callerValue).toBe(expected);
152153
},
153154
);
155+
156+
test.each([
157+
['react-server', 'react-server'],
158+
[undefined, undefined],
159+
[null, undefined],
160+
])(
161+
'with environment: %s, exposes it on the caller: %s',
162+
(environment, expected) => {
163+
let callerValue;
164+
transform({
165+
filename: 'foo.js',
166+
src: 'console.log("foo");',
167+
plugins: [
168+
babel => {
169+
callerValue = babel.caller(caller => caller?.environment);
170+
return {visitor: {}};
171+
},
172+
],
173+
options: {
174+
dev: true,
175+
enableBabelRuntime: false,
176+
enableBabelRCLookup: false,
177+
environment,
178+
globalPrefix: '__metro__',
179+
minify: false,
180+
platform: null,
181+
publicPath: 'test',
182+
projectRoot: PROJECT_ROOT,
183+
},
184+
});
185+
expect(callerValue).toBe(expected);
186+
},
187+
);

‎packages/metro-babel-transformer/src/index.js‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ type BabelTransformerOptions = Readonly<{
3939
dev: boolean,
4040
enableBabelRCLookup?: boolean,
4141
enableBabelRuntime: boolean | string,
42+
environment?: ?string,
4243
extendsBabelConfigPath?: string,
4344
experimentalImportSupport?: boolean,
4445
hermesParser?: boolean,
@@ -101,6 +102,11 @@ function transform(
101102
? 'development'
102103
: process.env.BABEL_ENV || 'production';
103104

105+
// Only present when set, like the Babel runtime fields, so that the caller is
106+
// unchanged for bundles without an environment.
107+
const environmentCaller: {environment?: string} =
108+
options.environment != null ? {environment: options.environment} : {};
109+
104110
try {
105111
const babelConfig: BabelTransformOptions = {
106112
ast: true,
@@ -122,6 +128,7 @@ function transform(
122128
: null),
123129
// Whether `metro:inline` specifiers will resolve.
124130
supportsInlineModules: options.supportsInlineModules,
131+
...environmentCaller,
125132
},
126133
// NOTE(EvanBacon): We split the parse/transform steps up to accommodate
127134
// Hermes parsing, but this defaults to cloning the AST which increases

‎packages/metro-resolver/API.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ export type ResolutionContext = Readonly<{
6565
disableHierarchicalLookup: boolean;
6666
extraNodeModules: null | undefined | {[packageName: string]: string};
6767
dev: boolean;
68+
environment?: null | undefined | string;
6869
getPackage: (packageJsonPath: string) => null | undefined | PackageJson;
6970
getPackageForModule: (absoluteModulePath: string) => null | undefined | PackageForModule;
7071
dependency?: TransformResultDependency | undefined;

‎packages/metro-resolver/src/types.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,12 @@ export type ResolutionContext = Readonly<{
158158
/** Is resolving for a development bundle. */
159159
dev: boolean,
160160

161+
/**
162+
* The environment to bundle for, e.g. `'react-server'`. Absent for the
163+
* default environment.
164+
*/
165+
environment?: ?string,
166+
161167
/**
162168
* Get the parsed contents of the specified `package.json` file.
163169
*/

‎packages/metro-transform-worker/API.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ export type JsTransformerConfig = Readonly<{
5252
export type JsTransformOptions = Readonly<{
5353
customTransformOptions?: CustomTransformOptions | undefined;
5454
dev: boolean;
55+
environment?: null | undefined | string;
5556
experimentalImportSupport?: boolean | undefined;
5657
inlinePlatform: boolean;
5758
inlineRequires: boolean;

‎packages/metro-transform-worker/src/index.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ export type {CustomTransformOptions} from 'metro-babel-transformer';
134134
export type JsTransformOptions = Readonly<{
135135
customTransformOptions?: CustomTransformOptions,
136136
dev: boolean,
137+
environment?: ?string,
137138
experimentalImportSupport?: boolean,
138139
inlinePlatform: boolean,
139140
inlineRequires: boolean,

‎packages/metro/API.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ export type RunBuildOptions = {
224224
entry: string;
225225
assets?: boolean | undefined;
226226
dev?: boolean | undefined;
227+
environment?: string | undefined;
227228
out?: string | undefined;
228229
bundleOut?: string | undefined;
229230
sourceMapOut?: string | undefined;

0 commit comments

Comments
 (0)