### Metro Bundling API - Quick Start Examples Source: https://github.com/facebook/metro/blob/main/docs/API.md Provides quick start examples for common Metro bundling tasks like compiling a file, running a development server, and creating Connect middleware. ```APIDOC ## Quick Start Examples ### Compile a file ```js const config = await Metro.loadConfig(); await Metro.runBuild(config, { entry: 'index.js', out: 'bundle.js', }); ``` ### Run a server and watch the filesystem for changes ```js const config = await Metro.loadConfig(); await Metro.runServer(config); ``` ### Create a Connect middleware and plug it into a server ```js const Metro = require('metro'); const express = require('express'); const app = express(); const server = require('http').Server(app); Metro.loadConfig().then(async config => { const connectMiddleware = await Metro.createConnectMiddleware(config); const {server: {port}} = config; app.use(connectMiddleware.middleware); server.listen(port); connectMiddleware.attachHmrServer(server); }); ``` ``` -------------------------------- ### Install Metro with yarn Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Install Metro and metro-core as development dependencies using yarn. ```bash yarn add --dev metro metro-core ``` -------------------------------- ### Install Metro with npm Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Install Metro and metro-core as development dependencies using npm. ```bash npm install --save-dev metro metro-core ``` -------------------------------- ### Metro.runServer(config, options) Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Starts a development server based on the provided configuration and options. ```APIDOC ## runServer(config, options) ### Description Starts a development server. Returns an object containing the `httpServer` instance. ### Parameters - **config** (Object) - Required - The configuration object. - **options** (Object) - Optional - Configuration options for the server. - **host** (string) - Optional - Host address. - **onReady** (Function) - Optional - Callback when server is ready. - **onClose** (Function) - Optional - Callback when server closes. - **secureServerOptions** (Object) - Optional - HTTPS server options. - **waitForBundler** (boolean) - Optional - Whether to wait for bundler initialization. ### Response - **httpServer** (Object) - The Node.js HTTP(S) server instance. ``` -------------------------------- ### Metro CLI Serve Command Source: https://github.com/facebook/metro/blob/main/docs/CLI.md Starts Metro on the given port, building bundles on the fly. ```APIDOC ## `serve` Starts Metro on the given port, building bundles on the fly. ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/facebook/metro/blob/main/CONTRIBUTING.md Install project dependencies using Yarn. This command should be run after cloning the repository. ```sh yarn ``` -------------------------------- ### Metro CLI Get Dependencies Command Source: https://github.com/facebook/metro/blob/main/docs/CLI.md Lists all dependencies that will be bundled for a given entry point. ```APIDOC ## `get-dependencies ` List all dependencies that will be bundled for a given entry point. ### Options | Option | Description | |---|---| | `entry-file` | Absolute path to the root JS file. This can also be given as the first positional arg. | | `output` | File name where to store the output, ex. /tmp/dependencies.txt | | `platform` | The platform extension used for selecting modules | | `transformer` | Specify a custom transformer to be used | | `max-workers` | Specifies the maximum number of workers the worker-pool will spawn for transforming files. This defaults to the number of the cores available on your machine. | | `dev` | If false, skip all dev-only code path | | `verbose` | Enables logging | ``` -------------------------------- ### Example of Enhancing Metro Middleware Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Demonstrates how to extend the base `metroMiddleware` with custom middleware using `connect()`. This example mounts a custom endpoint. ```typescript enhanceMiddleware: (metroMiddleware: Middleware, metroServer: MetroServer) => { return connect() .use(metroMiddleware) .use('/custom-endpoint', customEndpointMiddleware()); } ``` -------------------------------- ### Importing a node_module Source: https://github.com/facebook/metro/blob/main/docs/Resolution.md Example of importing a module from the node_modules directory. ```javascript // src/App.js import {View} from 'react-native'; // ... ``` -------------------------------- ### Importing a local file Source: https://github.com/facebook/metro/blob/main/docs/Resolution.md Example of importing a local component file using a relative path. ```javascript // src/App.js import Comp from './Component'; // ... ``` -------------------------------- ### Run Metro server and watch filesystem Source: https://github.com/facebook/metro/blob/main/docs/API.md Starts a Metro server that watches for file changes and recompiles bundles as needed. Load the configuration before running the server. ```javascript const config = await Metro.loadConfig(); await Metro.runServer(config); ``` -------------------------------- ### Metro Bundling API - runServer Source: https://github.com/facebook/metro/blob/main/docs/API.md Starts a full Metro HTTP server that listens on a specified host and port, serving bundles for various entry points. ```APIDOC ## async runServer(config, ) ### Description Starts a full Metro HTTP server. It will listen on the specified `host:port`, and can then be queried to retrieve bundles for various entry points. If the `secureServerOptions` family of options are present, the server will be exposed over HTTPS. `secure`, `secureKey`, `secureCert` are now deprecated and will be removed in a later release. The presence of `secureServerOptions`, along with its options will make Metro run over https. ### Method `runServer` ### Parameters #### Path Parameters - **config** (object) - Required - The Metro configuration object. #### Basic options: - **host** (string) - Optional - The host to listen on. - **port** (number) - Optional - The port to listen on. - **secureServerOptions** (object) - Optional - Options for configuring HTTPS. - **secure** (boolean) - DEPRECATED - Whether to use HTTPS. - **secureKey** (string) - DEPRECATED - The path to the SSL key file. - **secureCert** (string) - DEPRECATED - The path to the SSL certificate file. ``` -------------------------------- ### Run Metro Website Server Source: https://github.com/facebook/metro/blob/main/website/README.md Starts the development server for the Metro website. Access the site at http://localhost:3000. Changes are automatically updated on refresh. ```bash npm start ``` -------------------------------- ### Run Metro and hook into HTTP server Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Load configuration, run Metro, and create an HTTP server using its processRequest method. This example demonstrates how to integrate Metro's bundler with a Node.js HTTP server. ```javascript 'use strict'; const http = require('http'); const Metro = require('metro'); // We first load the config from the file system Metro.loadConfig().then(async (config) => { const metroBundlerServer = await Metro.runMetro(config); const httpServer = http.createServer( metroBundlerServer.processRequest.bind(metroBundlerServer), ); httpServer.listen(8081); }); ``` -------------------------------- ### Define package.json exports Source: https://github.com/facebook/metro/blob/main/docs/PackageExports.md Example configuration for a package using the exports field to define entry points for different module systems. ```json { "name": "some-pkg", "version": "1.0.0", "main": "./dist/cjs/index.js", "exports": { ".": { "import": "./dist/esm/index.mjs", "require": "./dist/cjs/index.js" } } } ``` -------------------------------- ### Import package using exports Source: https://github.com/facebook/metro/blob/main/docs/PackageExports.md Examples of how Metro resolves imports based on the module system used. ```js import Foo from 'some-pkg'; ``` ```js const Foo = require('some-pkg'); ``` -------------------------------- ### Run Metro server with onClose callback Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Start a Metro development server and log a message when the server and all associated processes are closed. This is useful for cleanup operations. ```javascript const config = await Metro.loadConfig(); await Metro.runServer(config, { onClose: () => {console.log('metro server and all associated processes are closed')} }); httpServer.on('close', () => {console.log('metro server is closed')}); ``` -------------------------------- ### Run Metro server with HTTPS options Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Start a Metro development server using HTTPS by providing secure server options, including CA, certificate, and key paths. This is for secure development environments. ```javascript const fs = require('fs'); const config = await Metro.loadConfig(); await Metro.runServer(config, { secureServerOptions: { ca: fs.readFileSync('path/to/ca'), cert: fs.readFileSync('path/to/cert'), key: fs.readFileSync('path/to/key'), } }); ``` -------------------------------- ### Run Metro Development Server Source: https://github.com/facebook/metro/blob/main/docs/LocalDevelopment.md Start the Metro development server within your target project. Remember to restart this command after making code changes to Metro or the target project's `metro.config.js`. ```sh yarn react-native start ``` -------------------------------- ### Implement a no-op performance logger factory Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md An example implementation of a factory function that returns a no-op RootPerfLogger. ```javascript const unstable_perfLoggerFactory = (type, factoryOpts) => { const getLogger = subSpanLabel => { const logger = { start(opts) {}, end(status, opts) {}, subSpan(label) { return getLogger(`${subSpanLabel ?? ''}/${label}`); }, point(name, opts) {}, annotate(annotations) {}, }; return logger; }; return getLogger(); }; ``` -------------------------------- ### Example Source Map Structure Source: https://github.com/facebook/metro/blob/main/docs/SourceMapFormat.md A sample source map JSON object illustrating the `mappings` field and associated metadata. Note that comments are for explanation and not part of the actual source map format. ```json { "version": 3, "sources": ["file.js"], "sourcesContent": ["function a(){} function b(){}"], "mappings": "AAAA", // NOTE: Simplified "x_facebook_sources": [ // Metadata tuple for source #0 (file.js) [ // Metadata item #0.0 = function map for source #0 (file.js) { // a from 1:0 // from 1:14 // b from 1:15 // (See detailed decoding procedure below.) "mappings": "AAA,cC,CC", "names": [ "a", "", "b", ] } ] ] } ``` -------------------------------- ### Configure Cache Stores with FileStore Source: https://github.com/facebook/metro/blob/main/docs/Caching.md Example of configuring Metro to use a local file-based cache store. Ensure the `FileStore` is imported from `metro-cache` or accessed via the `cacheStores` function. ```javascript const os = require('node:os'); const path = require('node:path'); module.exports = { cacheStores: ({ FileStore }) => [ new FileStore({ root: path.join(os.tmpdir(), 'metro-cache'), }), ], }; ``` -------------------------------- ### GET /{path}.bundle Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Requests a bundle for a specific JavaScript file via URL, supporting various build options as query parameters. ```APIDOC ## GET /{path}.bundle ### Description Requests a bundle for a JS file. The file is looked up in the projectRoot, and all required files are recursively included. ### Query Parameters - **dev** (string) - Optional - Build in development mode ('true' or 'false'). - **platform** (string) - Optional - Platform requesting the bundle ('ios' or 'android'). - **minify** (string) - Optional - Whether code should be minified ('true' or 'false'). - **excludeSource** (string) - Optional - Whether sources should be included in the source map ('true' or 'false'). ### Request Example http://localhost:8081/foo/bar/baz.bundle?dev=true&platform=ios ``` -------------------------------- ### Define exports subpath Source: https://github.com/facebook/metro/blob/main/docs/PackageExports.md Example of mapping a specific subpath in the exports field. ```json { "name": "some-pkg", "exports": { "./FooComponent": "./src/FooComponent.js" } } ``` -------------------------------- ### Enable Metro Debug Logging Source: https://github.com/facebook/metro/blob/main/docs/LocalDevelopment.md Set the `DEBUG` environment variable to `Metro:*` before starting Metro to enable logs matching all Metro-defined debug scopes. This is useful for diagnosing issues within Metro. ```sh DEBUG='Metro:*' yarn metro serve ``` -------------------------------- ### Create Connect middleware for Metro Source: https://github.com/facebook/metro/blob/main/docs/API.md Integrates Metro's bundling capabilities into an existing Express server by creating a Connect middleware. This allows Metro to handle bundle requests within your custom server setup and enables Hot Module Replacement (HMR). ```javascript const Metro = require('metro'); const express = require('express'); const app = express(); const server = require('http').Server(app); Metro.loadConfig().then(async config => { const connectMiddleware = await Metro.createConnectMiddleware(config); const {server: {port}} = config; app.use(connectMiddleware.middleware); server.listen(port); connectMiddleware.attachHmrServer(server); }); ``` -------------------------------- ### Merge Metro Configurations Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Use `mergeConfig` to combine multiple Metro configuration objects and functions. This example shows merging two configuration objects and a configuration function that modifies watch folders. ```javascript // metro.config.js const { mergeConfig } = require('metro-config'); const configA = { /* general options */ resolver: { /* resolver options */ }, transformer: { /* transformer options */ }, serializer: { /* serializer options */ }, server: { /* server options */ } }; const configB = { /* general options */ resolver: { /* resolver options */ }, transformer: { /* transformer options */ }, serializer: { /* serializer options */ }, server: { /* server options */ } }; // Function forms may be used to access the previous configuration configCFn = (previousConfig /* result of mergeConfig(configA, configB) */) => { return { watchFolders: [...previousConfig.watchFolders, 'my-watch-folder'], } } module.exports = mergeConfig(configA, configB, configCFn); ``` -------------------------------- ### Configure Babel Runtime in Metro Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Use `@babel/transform/runtime` for transforming JavaScript. Pass a version string to optimize runtime calls based on your project's installed version. ```typescript enableBabelRuntime: true | string ``` -------------------------------- ### Metro.runMetro(config) Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Initializes a Metro server instance that can be integrated into existing HTTP(S) or Express servers. ```APIDOC ## runMetro(config) ### Description Initializes a metro-server instance. The returned object provides a `processRequest` method that can be used to handle incoming HTTP requests. ### Parameters - **config** (Object) - Required - The configuration object loaded via `Metro.loadConfig()`. ### Response - **metro-server** (Object) - An instance containing the `processRequest` method. ``` -------------------------------- ### Metro Bundling API - runMetro Source: https://github.com/facebook/metro/blob/main/docs/API.md Creates and returns a Metro server based on the provided configuration, which can be used as middleware in an existing server. ```APIDOC ## async runMetro(config) ### Description Creates a Metro server based on the config and returns it. You can use this as a middleware in your existing server. ### Method `runMetro` ### Parameters #### Path Parameters - **config** (object) - Required - The Metro configuration object. ``` -------------------------------- ### Publish Metro Website (Staging/Fork Deployment) Source: https://github.com/facebook/metro/blob/main/website/README.md Deploys the Metro website to your own fork for staging. Replace YOUR_GITHUB_USERNAME with your GitHub username. ```bash DEPLOY_USER=YOUR_GITHUB_USERNAME GIT_USER=YOUR_GITHUB_USERNAME CIRCLE_PROJECT_USERNAME=YOUR_GITHUB_USERNAME CIRCLE_PROJECT_REPONAME=metro npm run gh-pages ``` -------------------------------- ### Metro Bundling API - runBuild Source: https://github.com/facebook/metro/blob/main/docs/API.md Bundles an entry point for a specified platform and saves it to an output location. Supports source map generation and asset collection. ```APIDOC ## async runBuild(config, ) ### Description Bundles `entry` for the given `platform`, and saves it to location `out`. If `sourceMap` is set, also generates a source map. The source map will be inlined, unless `sourceMapUrl` is also defined. In the latter case, a new file will be generated with the basename of the `sourceMapUrl` parameter. If `assets` is `true`, an array of `AssetData` will be generated and returned in the `assets` property of the result object. ### Method `runBuild` ### Parameters #### Path Parameters - **config** (object) - Required - The Metro configuration object. #### Required options: - **entry** (string) - The entry file for the bundle. - **out** (string) - The output path for the bundle. #### Basic options: - **dev** (boolean) - Optional - Whether to enable development mode. - **minify** (boolean) - Optional - Whether to minify the bundle. - **platform** (string) - Optional - The target platform (e.g., 'ios', 'android'). - **sourceMap** (boolean) - Optional - Whether to generate a source map. - **sourceMapUrl** (string) - Optional - The URL for the source map. - **assets** (boolean) - Optional - Whether to generate asset data. ``` -------------------------------- ### Metro Configuration Options Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Configuration settings for Metro startup, performance, and caching behavior. ```APIDOC ## Metro Configuration Options ### Parameters - **resetCache** (boolean) - Optional - If true, Metro will reset the transformer and file map cache on startup. - **stickyWorkers** (boolean) - Optional - If true, uses a stable mapping from files to transformer workers. Defaults to true. - **maxWorkers** (number) - Optional - Number of workers for parallel processing. Defaults to approximately half of available cores. - **fileMapCacheDirectory** (string) - Optional - Path to the metro-file-map cache directory. Defaults to os.tmpdir(). - **hasteMapCacheDirectory** (string) - Deprecated - Alias of fileMapCacheDirectory. - **unstable_perfLoggerFactory** (PerfLoggerFactory) - Optional - A logger factory function for performance insights. ``` -------------------------------- ### Metro.runBuild(config, options) Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Executes a build process using the provided Metro configuration and build options. ```APIDOC ## Metro.runBuild(config, options) ### Description Executes a build process to bundle files based on the provided configuration and options. ### Parameters #### Options - **assets** (boolean) - Optional - Whether to include assets in the result. - **bundleOut** (string) - Optional - Path to save the bundle. - **dev** (boolean) - Optional - Create a development version of the build. - **entry** (string) - Optional - Pointing to the entry file to bundle. - **onBegin** (Function) - Optional - Called when the bundling starts. - **onComplete** (Function) - Optional - Called when the bundling finishes. - **onProgress** (Function) - Optional - Called during the bundle for progress updates. - **minify** (boolean) - Optional - Whether Metro should minify the bundle. - **out** (string) - Optional - Shorthand path to the output bundle and source map. - **platform** ('web' | 'android' | 'ios') - Optional - Which platform to bundle for. - **sourceMap** (boolean) - Optional - Whether Metro should generate source maps. - **sourceMapOut** (string) - Optional - Where to save the source map. - **sourceMapUrl** (string) - Optional - URL where the source map can be found. ### Request Example ```js const config = await Metro.loadConfig(); await Metro.runBuild(config, { entry: 'index.js', platform: 'ios', minify: true, out: '/Users/Metro/metro-ios.js' }); ``` ``` -------------------------------- ### Custom Cache Store Interface Source: https://github.com/facebook/metro/blob/main/docs/Caching.md Defines the interface for implementing a custom cache store in Metro. This includes methods for getting, setting, and clearing cache entries. ```typescript interface CacheStore { // Read an entry from the cache. Returns `null` if not found. get(key: Buffer): ?T | Promise; // Write an entry to the cache (if writable) or do nothing (if read-only) set(key: Buffer, value: T): void | Promise; // Clear the cache (if possible) or do nothing clear(): void | Promise; } type JsonSerializable = /* Any JSON-serializable value */; ``` -------------------------------- ### Metro.runBuild(config, options) Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Performs a build of the bundle based on the provided configuration and options. ```APIDOC ## runBuild(config, options) ### Description Builds a bundle and returns the resulting code, map, and assets. ### Parameters - **config** (Object) - Required - The configuration object. - **options** (Object) - Optional - Build-specific options. ### Response - **Promise** - Resolves to an object containing `code`, `map`, and optionally `assets`. ``` -------------------------------- ### Metro.createConnectMiddleware(config) Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Creates a Connect middleware that handles bundle requests, suitable for integration into existing servers. ```APIDOC ## Metro.createConnectMiddleware(config) ### Description Creates a Connect middleware that answers to bundle requests. This middleware can be plugged into custom servers. ### Parameters #### Options - **port** (number) - Optional - Port for the Connect middleware (used for logging). ### Request Example ```js const connectMiddleware = await Metro.createConnectMiddleware(config); app.use(connectMiddleware.middleware); ``` ``` -------------------------------- ### Metro CLI Build Command Source: https://github.com/facebook/metro/blob/main/docs/CLI.md Generates a JavaScript bundle from a specified entry point. ```APIDOC ## `build ` Generates a JavaScript bundle containing the specified entrypoint and its descendants. ### Options | Option | Alias | Description | Value | |----------|----------|----------|----------| | `out` | `O` | File name where to store the output | String | | `platform` | `p` | Which platform to bundle for | `web`, `android`, `ios` | | `minify` | `z` | Whether Metro should minify the bundle | Boolean | | `dev` | `g` | Create a development version of the build (`process.env.NODE_ENV = 'development'`) | Boolean | | `config` | `c` | Location of the `metro.config.js` to use | String | | `max-workers` | `j` | The number of workers Metro should parallelize the transformer on | Number | | `project-roots` | `P` | The root folder of your project | Array | | `source-map` | | Whether Metro should generate source maps | Boolean | | `source-map-url` | | URL where the source map can be found | String | | `legacy-bundler` | | Whether Metro should use the legacy bundler | Boolean | | `resolver-option` | | [Custom resolver options](./Resolution.md#customresolveroptions-string-mixed) of the form `key=value` | Array | | `transform-option` | | Custom transform options of the form `key=value` | Array | ``` -------------------------------- ### Specify Modules to Run Before Entry Point Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Provide an array of absolute module paths to be required before the main entry point. This only adds require statements if the modules are already part of the bundle. ```typescript getModulesRunBeforeMainModule: (entryFilePath: string) => Array ``` -------------------------------- ### Compile a file using Metro Source: https://github.com/facebook/metro/blob/main/docs/API.md Use this snippet to compile a single entry file into a bundle. Ensure Metro configuration is loaded first. ```javascript const config = await Metro.loadConfig(); await Metro.runBuild(config, { entry: 'index.js', out: 'bundle.js', }); ``` -------------------------------- ### Publish Metro Website (Manual Deployment) Source: https://github.com/facebook/metro/blob/main/website/README.md Deploys the Metro website manually. Requires Git write permissions. This command pushes the generated static site to the gh-pages branch. ```bash DEPLOY_USER=facebook GIT_USER=metro-bot CIRCLE_PROJECT_USERNAME=facebook CIRCLE_PROJECT_REPONAME=metro npm run gh-pages ``` -------------------------------- ### Build a bundle programmatically Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Use Metro.runBuild to generate a bundle based on a loaded configuration. Ensure the entry file path and output destination are correctly specified. ```javascript const config = await Metro.loadConfig(); await Metro.runBuild(config, { entry: 'index.js', platform: 'ios', minify: true, out: '/Users/Metro/metro-ios.js' }); ``` -------------------------------- ### Clone Metro Repository and Create Branch Source: https://github.com/facebook/metro/blob/main/CONTRIBUTING.md Clone the Metro repository and create a new branch for your contributions. This is the first step in the development workflow. ```sh git clone https://github.com/facebook/metro cd metro git checkout -b my_branch ``` -------------------------------- ### Implement platform-specific selection Source: https://github.com/facebook/metro/blob/main/docs/PackageExports.md Use Platform.select to handle platform-specific logic instead of relying on file extensions in exports. ```json "exports": { "./FooComponent": "./src/FooComponent.js" } ``` ```js // src/FooComponent.js const FooComponent = Platform.select({ android: require('./FooComponentAndroid.js'), ios: require('FooComponentIOS.js'), }); export default FooComponent; ``` -------------------------------- ### import() Source: https://github.com/facebook/metro/blob/main/docs/ModuleAPI.md Supports dynamic imports to enable code splitting and faster loading. ```APIDOC ## import(modulePath) ### Description Dynamically imports a module. In React Native, this automatically splits application code for performance. ### Parameters #### Path Parameters - **modulePath** (string) - Required - The path to the module to be loaded dynamically. ``` -------------------------------- ### Metro Bundling API - createConnectMiddleware Source: https://github.com/facebook/metro/blob/main/docs/API.md Creates a Connect middleware for handling bundle requests, which can be integrated into custom servers. ```APIDOC ## createConnectMiddleware(config, ) ### Description Instead of creating the full server, creates a Connect middleware that answers to bundle requests. This middleware can then be plugged into your own servers. The `port` parameter is optional and only used for logging purposes. The `onBundleBuilt` function is optional, is passed the bundle name, and is called when the server has finishing creating the bundle. ### Method `createConnectMiddleware` ### Parameters #### Path Parameters - **config** (object) - Required - The Metro configuration object. #### Basic options: - **port** (number) - Optional - The port number for logging purposes. - **onBundleBuilt** (function) - Optional - A callback function that is called when a bundle is built. ``` -------------------------------- ### Define package subpaths Source: https://github.com/facebook/metro/blob/main/docs/PackageExports.md Use extensionless specifiers or define both extensioned and extensionless specifiers for backwards compatibility. ```json "exports": { ".": "./src/index.js", "./FooComponent": "./src/FooComponent.js", "./FooComponent.js": "./src/FooComponent.js" } ``` -------------------------------- ### Import subpath with extension Source: https://github.com/facebook/metro/blob/main/docs/PackageExports.md Demonstrates that import specifiers must match the exports key exactly, including extensions. ```js import FooComponent from 'some-pkg/FooComponent.js'; // Inaccessible unless the package had also listed "./FooComponent.js" // as an "exports" key ``` -------------------------------- ### Metro Configuration Options Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md A collection of configuration properties used to customize Metro's behavior, including resolution strategies, file system interactions, and platform support. ```APIDOC ## Metro Configuration Options ### Description Configuration options for the Metro bundler to control module resolution, file system watching, and project structure. ### Parameters - **disableHierarchicalLookup** (boolean) - Optional - Whether to disable looking up modules in node_modules folders. Defaults to false. - **emptyModulePath** (string) - Optional - Canonical path for the empty module. Defaults to metro-runtime. - **enableGlobalPackages** (boolean) - Optional - Whether to automatically resolve references to first-party packages. Defaults to false. - **extraNodeModules** ({[string]: string}) - Optional - Mapping of package names to directories for resolution. - **nodeModulesPaths** (Array) - Optional - List of paths to check for modules after node_modules. - **resolveRequest** (CustomResolver) - Optional - Function to override the default resolution algorithm. - **useWatchman** (boolean) - Optional - Whether to use Watchman for file watching. - **blockList** (RegExp or Array) - Optional - Paths to exclude from Metro's file map. - **hasteImplModulePath** (string) - Optional - Path to the Haste implementation module. - **platforms** (Array) - Optional - Additional platforms to resolve. Defaults to ['ios', 'android', 'windows', 'web']. - **requireCycleIgnorePatterns** (Array) - Optional - Patterns to suppress require cycle warnings. ``` -------------------------------- ### Basic Metro Configuration Structure Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md A common configuration structure in Metro, outlining the main sections for resolver, transformer, serializer, server, and watcher options. ```javascript module.exports = { /* general options */ resolver: { /* resolver options */ }, transformer: { /* transformer options */ }, serializer: { /* serializer options */ }, server: { /* server options */ }, watcher: { /* watcher options */ watchman: { /* Watchman-specific options */ } } }; ``` -------------------------------- ### Server Options Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Options that control how the Metro server operates. ```APIDOC ## Server Options These options are used when Metro serves the content. ### `port` Type: `number` Which port to listen on. ### `useGlobalHotkey` Type: `boolean` Whether we should enable CMD+R hotkey for refreshing the bundle. ### `enhanceMiddleware`
Deprecated
Type: `(Middleware, MetroServer) => Middleware` A function that allows attaching custom [`connect`](https://www.npmjs.com/package/connect) middleware to Metro. For example: :::tip You can use [`connect()`](https://www.npmjs.com/package/connect#mount-middleware) as a utility to extend the base `metroMiddleware` and to mount additional middleware handlers. ::: ```ts enhanceMiddleware: (metroMiddleware: Middleware, metroServer: MetroServer) => { return connect() .use(metroMiddleware) .use('/custom-endpoint', customEndpointMiddleware()); }, ``` The `Middleware` type is an alias for [`connect.HandleFunction`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/876b9ec96ba02d0c84b1e49af5890c8f5aa2dfe3/types/connect/index.d.ts#L29). ### `rewriteRequestUrl` Type: `string => string` A function that will be called every time Metro processes a "URL" (see note), after normalization of non-standard query-string delimiters using [`jsc-safe-url`](https://www.npmjs.com/package/jsc-safe-url). Metro will use the return value of this function as if it were the original URL provided by the client. This applies to all incoming HTTP requests (after any custom middleware), as well as bundle URLs in `/symbolicate` request payloads and within the hot reloading protocol. :::note The input may be either an absolute URL (e.g. `https://example.com/foo/bar?baz=qux`) or a path (e.g. `/foo/bar?baz=qux`). The output should use the same form as the input - i.e. the returned value should be an absolute URL if and only if the input is an absolute URL. ::: ``` -------------------------------- ### require() Source: https://github.com/facebook/metro/blob/main/docs/ModuleAPI.md The require() function is used to load modules by name or path, similar to Node.js. It evaluates the module and returns the exported value. ```APIDOC ## require(id) ### Description Loads a module by name or path. Modules referenced by require() are added to the bundle. ### Parameters #### Path Parameters - **id** (string) - Required - The module name or path to resolve. ### Request Example ```js const localModule = require('./path/module'); const asset = require('./path/asset.png'); ``` ``` -------------------------------- ### Resolver Options Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Configuration settings for how Metro resolves modules and assets. ```APIDOC ## Resolver Options ### Parameters - **assetExts** (Array) - Optional - List of asset file extensions to include in the bundle. - **sourceExts** (Array) - Optional - List of source file extensions to include in the bundle. Defaults to ['js', 'jsx', 'json', 'ts', 'tsx']. - **resolverMainFields** (Array) - Optional - List of fields in package.json that Metro treats as entry points. Defaults to ['browser', 'main']. ``` -------------------------------- ### Customize Initial Require Statements Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Specify the format for initial `require` statements appended to the bundle. The default format is `__r(${moduleId});`. ```typescript getRunModuleStatement: (moduleId: number | string, globalPrefix: string) => string ``` -------------------------------- ### Basic require() usage Source: https://github.com/facebook/metro/blob/main/docs/ModuleAPI.md Use require() to import local modules, assets, JSON files, or React Native components. The argument must be a compile-time constant. ```javascript const localModule = require('./path/module'); const asset = require('./path/asset.png'); const jsonData = require('./path/data.json'); const {View} = require('react-native'); ``` -------------------------------- ### Configure conditional exports Source: https://github.com/facebook/metro/blob/main/docs/PackageExports.md Define resolution order for different environments by specifying conditions like browser, react-native, and default. ```json "exports": { "browser": "./dist/index-browser.js", "react-native": "./dist/index-react-native.js", "default": "./dist/index.js" } ``` -------------------------------- ### Configure TLS Options Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Defines the structure for TLS configuration when enabling HTTPS in Metro. ```ts ca?: string | Buffer, // Certificate authority (contents, not path) cert?: string | Buffer, // Server certificate (contents, not path) key?: string | Buffer, // Private key (contents, not path) requestCert?: boolean, // Whether to authenticate the remote peer by requesting a certificate ``` -------------------------------- ### Export asset files with patterns Source: https://github.com/facebook/metro/blob/main/docs/PackageExports.md Use subpath patterns to export multiple assets, ensuring file extensions are included. ```json { "exports": { "./assets/*.png": "./dist/assets/*.png" } } ``` -------------------------------- ### Metro Bundling API - loadConfig Source: https://github.com/facebook/metro/blob/main/docs/API.md Loads the Metro configuration. It can load from a specified config option or by traversing the directory hierarchy to find a configuration file. ```APIDOC ## loadConfig() ### Description Loads the Metro configuration, either from `config` in options if specified, or by traversing the directory hierarchy from `cwd` to the root until it finds a file (by default `metro.config.js`). The returned configuration will have been normalized and merged with Metro's default values. ### Method `loadConfig` ### Parameters #### Basic options: - **config** (object) - Optional - The Metro configuration object. - **cwd** (string) - Optional - The current working directory to start searching for the config file. ``` -------------------------------- ### Resolver Configuration Options Source: https://github.com/facebook/metro/blob/main/docs/Resolution.md Boolean flags and configuration objects that control the behavior of the module resolver. ```APIDOC ## `isESMImport?: boolean` ### Description Indicates whether the dependency was declared using an ESM import (`import` or `await import()`) or a CommonJS `require`. This corresponds to Node.js's criteria for 'import' vs 'require' resolution conditions. It is typically equal to `dependency.data.isESMImport` but can be used independently for resolution. ### Method N/A (Configuration Option) ### Endpoint N/A ## `allowHaste: boolean` ### Description `true` if Haste resolutions are allowed in the current context, `false` otherwise. ### Method N/A (Configuration Option) ### Endpoint N/A ## `disableHierarchicalLookup: boolean` ### Description If `true`, the resolver will not perform lookups in `node_modules` directories according to the standard Node resolution algorithm. Defaults to `resolver.disableHierarchicalLookup`. ### Method N/A (Configuration Option) ### Endpoint N/A ## `extraNodeModules: ?{[string]: string}` ### Description A mapping of package names to directories that is consulted after the standard lookup through `node_modules` and any `nodeModulesPaths`. ### Method N/A (Configuration Option) ### Endpoint N/A ## `originModulePath: string` ### Description The absolute path to the current module, for example, the module containing the `import` statement being resolved. ### Method N/A (Configuration Option) ### Endpoint N/A ## `customResolverOptions: {[string]: mixed}` ### Description Any custom options passed to the resolver. By default, Metro populates this based on URL parameters in the bundle request (e.g., `http://localhost:8081/index.bundle?resolver.key=value` becomes `{key: 'value'}`). ### Method N/A (Configuration Option) ### Endpoint N/A ``` -------------------------------- ### Configure Metro Watch Folders Source: https://github.com/facebook/metro/blob/main/docs/LocalDevelopment.md Update your `metro.config.js` to include the necessary file paths for `yarn link`ed modules. This ensures Metro follows symlinks and recognizes changes in your linked packages. ```javascript const path = require('path'); module.exports = { watchFolders: [ path.resolve(__dirname, './node_modules'), // Include necessary file paths for `yarn link`ed modules path.resolve(__dirname, '../metro/packages'), path.resolve(__dirname, '../metro/node_modules'), ], ... }; ``` -------------------------------- ### Compare legacy and exports resolution Source: https://github.com/facebook/metro/blob/main/docs/PackageExports.md Comparison of resolution behavior for packages with and without an exports field. ```js import FooComponent from 'some-pkg/FooComponent'; // Tries .[platform].js, .native.js, .js (+ TypeScript variants) ``` ```js import FooComponent from 'some-pkg/FooComponent'; // Resolves exact target from "exports" only ``` -------------------------------- ### Transformer Configuration Options Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Configuration properties for controlling minification, asset management, and Babel transformation behavior. ```APIDOC ## Transformer Configuration Options ### Properties - **minifierPath** (string) - Path or package name to the minifier. - **minifierConfig** (Object) - Configuration object passed to the minifier. - **optimizationSizeLimit** (number) - Threshold in bytes to disable expensive optimizations for large files. - **assetPlugins** (Array) - List of modules to modify Asset data. - **assetRegistryPath** (string) - Path to fetch assets from. - **babelTransformerPath** (string) - Name of the module that compiles code with Babel. - **enableBabelRCLookup** (boolean) - Whether to enable searching for Babel configuration files. ``` -------------------------------- ### Metro Configuration Structure Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md The standard structure for a Metro configuration file, defining options for resolver, transformer, serializer, server, and watcher modules. ```APIDOC ## Metro Configuration Structure ### Description The configuration object defines how Metro behaves. It is typically exported from a `metro.config.js` file. ### Configuration Options - **cacheStores** (CacheStores) - Optional - A list of storage adapters for the transformer cache. - **cacheVersion** (string) - Optional - An arbitrary string appended to cache keys. - **projectRoot** (string) - Optional - The root folder of the project. - **watchFolders** (Array) - Optional - Directories outside of projectRoot that contain source files. - **transformerPath** (string) - Optional - Absolute path to a custom transformer module. - **reporter** (Object) - Optional - Object with an `update` method to report bundling status. ``` -------------------------------- ### Implement transform method with Babel core Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Integrates Babel by using transformSync to process the source code. ```js const {transformSync} = require('@babel/core'); module.exports.transform = file => { return transformSync(file.src, { // Babel options... }); }; ``` -------------------------------- ### Include Custom Polyfills Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Provide an optional list of polyfills to include in the bundle. Defaults to common polyfills for Number, String, and Array. ```typescript getPolyfills: ({platform: ?string}) => $ReadOnlyArray ``` -------------------------------- ### Transformer Options Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Configuration options for module transformation and dependency resolution. ```APIDOC ## Configuration: Transformer Options ### Description Settings that influence how modules are transformed and how dynamic dependencies are handled. ### Parameters - **asyncRequireModulePath** (string) - Optional - The name of a module that provides the asyncRequire function. (Deprecated) - **dynamicDepsInPackages** ('throwAtRuntime' | 'reject') - Optional - Controls how Metro handles dependencies that cannot be statically analyzed at build time. Defaults to 'throwAtRuntime'. ``` -------------------------------- ### Runtime require() with module ID Source: https://github.com/facebook/metro/blob/main/docs/ModuleAPI.md At runtime, require() accepts a module ID to retrieve a module. This is useful when you have a module ID from another API like require.resolveWeak(). ```javascript const localModule = require('./path/module'); const id = require.resolveWeak('./path/module'); // Bypass the restriction on non-constant require() arguments const dynamicRequire = require; dynamicRequire(id) === localModule; // true ``` -------------------------------- ### Serializer Options Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Options that control how the JavaScript bundle is serialized. ```APIDOC ## Serializer Options ### `getRunModuleStatement` Type: `(moduleId: number | string, globalPrefix: string) => string` Specify the format of the initial require statements that are appended at the end of the bundle. By default is `__r(${moduleId});`. ### `createModuleIdFactory` Type: `() => (path: string) => number` Used to generate the module id for `require` statements. ### `getPolyfills` Type: `({platform: ?string}) => $ReadOnlyArray` An optional list of polyfills to include in the bundle. The list defaults to a set of common polyfills for Number, String, Array, Object... ### `getModulesRunBeforeMainModule` Type: `(entryFilePath: string) => Array` An array of modules to be required before the entry point. It should contain the absolute path of each module. Note that this will add the additional require statements only if the passed modules are already included as part of the bundle. ### `processModuleFilter` Type: `(module: Array) => boolean` A filter function to discard specific modules from the output. ### `isThirdPartyModule` Type: `(module: {path: string, ...}) => boolean` A function that determines which modules are added to the [`x_google_ignoreList`](https://developer.chrome.com/articles/x-google-ignore-list/) field of the source map. This supports ["Just My Code"](https://developer.chrome.com/blog/devtools-modern-web-debugging/#just-my-code) debugging in Chrome DevTools and other compatible debuggers. Defaults to returning `true` for modules with a path component named `node_modules`. :::note In addition to modules marked as ignored by `isThirdPartyModule`, Metro will also automatically add modules generated by the bundler itself to the ignore list. ::: ``` -------------------------------- ### Enable Global Refresh Hotkey Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Toggle the CMD+R hotkey for refreshing the Metro bundle. Defaults to true. ```typescript useGlobalHotkey: boolean ``` -------------------------------- ### Define getTransformOptions function Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Implement this function to calculate custom options for the transformer and serializer based on the bundle being built. ```flow function getTransformOptions( entryPoints: $ReadOnlyArray, options: { dev: boolean, hot: boolean, platform: ?string, }, getDependenciesOf: (path: string) => Promise>, ): Promise { // ... } ``` -------------------------------- ### Package Exports Configuration Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Settings related to enabling and configuring Node.js package exports resolution in Metro. ```APIDOC ## Configuration: Package Exports ### Description These settings control how Metro resolves package entry points using the "exports" field in package.json. ### Parameters - **unstable_conditionNames** (Array) - Optional - The set of condition names to assert globally when interpreting the "exports" field. Defaults to ['require']. - **unstable_conditionsByPlatform** (Object) - Optional - Additional condition names to dynamically assert by platform. Defaults to { web: ['browser'] }. - **unstable_enablePackageExports** (boolean) - Optional - Enable experimental Package Exports support. Defaults to true. ``` -------------------------------- ### Link Local Metro Packages Source: https://github.com/facebook/metro/blob/main/docs/LocalDevelopment.md Use `yarn link` within your Metro clone to register local packages. This command links all packages in the Metro repository, allowing them to be individually linked into a target project. ```sh npm exec --workspaces -- yarn link ``` -------------------------------- ### Implement transform method with Babel parser Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Uses the default transformer approach to parse source code into an AST using @babel/parser. ```js const babylon = require('@babel/parser'); module.exports.transform = (file: {filename: string, src: string}) => { const ast = babylon.parse(file.src, {sourceType: 'module'}); return {ast}; }; ``` -------------------------------- ### Haste Implementation Signature Source: https://github.com/facebook/metro/blob/main/docs/Configuration.md Metro expects the Haste implementation module to export a `getHasteName` function. This function should return a unique name for a given file path or null if the module should not be accessible via Haste. ```flow module.exports = { getHasteName(filePath: string): ?string { // ... }, }; ``` -------------------------------- ### Define subpath patterns Source: https://github.com/facebook/metro/blob/main/docs/PackageExports.md Use a single asterisk for substring replacement to map multiple subpaths within a directory. ```json "exports": { ".": "./index.js", "./utils/*": "./utils/*.js" } ``` -------------------------------- ### JavaScript Source Map Mappings Decoding Procedure Source: https://github.com/facebook/metro/blob/main/docs/SourceMapFormat.md This JavaScript code demonstrates the step-by-step decoding process for the `mappings` field in a function map, converting VLQ encoded values into human-readable location data. It requires the `names` array from the source map. ```javascript const decoded = []; const names = ['a', '', 'b']; // From the function map let column = 0, nameIndex = 0, line = 1; column += 0 /* A */; nameIndex += 0 /* A */; line += 0 /* A */; decoded.push({column, name: names[nameIndex] /* 'a' */, line}); column += 14 /* c */; nameIndex += 1 /* C */; // no line delta decoded.push({column, name: names[nameIndex] /* '' */, line}); column += 1 /* C */; nameIndex += 1 /* C */; // no line delta decoded.push({column, name: names[nameIndex] /* 'b' */, line}); /* decoded = [ {column: 0, name: 'a', line: 1}, {column: 14, name: '', line: 1}, {column: 15, name: 'b', line: 1}, ] */ ``` -------------------------------- ### Require Metro module Source: https://github.com/facebook/metro/blob/main/docs/GettingStarted.md Load the Metro module to access its programmatic API. ```javascript const Metro = require('metro'); ```