|
| 1 | +import fs from "fs"; |
| 2 | +import path from "path"; |
| 3 | +import { createSerializer } from "react-native-bundle-discovery"; |
| 4 | +import { createServer } from "@discoveryjs/cli"; |
| 5 | +import discoveryrc from "react-native-bundle-discovery/.discoveryrc.js"; |
| 6 | + |
| 7 | +const id = Math.floor(Math.random() * 10); |
| 8 | +const fileName = `rozenite-metro-stats-${id}.json`; // Random name in case if multiple instances of Metro are running on different ports |
| 9 | +const defaultOutputJsonPath = path.resolve( |
| 10 | + path.dirname(new URL(import.meta.url).pathname), |
| 11 | + "../.stats", |
| 12 | + fileName, |
| 13 | +); |
| 14 | + |
| 15 | +try { |
| 16 | + fs.unlinkSync(defaultOutputJsonPath); |
| 17 | +} catch (e) { |
| 18 | + // Ignore if file does not exist |
| 19 | +} |
| 20 | + |
| 21 | +let outputJsonPath = defaultOutputJsonPath; |
| 22 | + |
| 23 | +function injectBundleDiscovery(config, options) { |
| 24 | + const hasSerializer = Boolean( |
| 25 | + config && config.serializer && config.serializer.customSerializer, |
| 26 | + ); |
| 27 | + |
| 28 | + outputJsonPath = (options && options.outputJsonPath) || defaultOutputJsonPath; |
| 29 | + |
| 30 | + const newSerializer = createSerializer({ |
| 31 | + projectRoot: process.cwd(), |
| 32 | + ...options, |
| 33 | + outputJsonPath, |
| 34 | + serializer: hasSerializer ? config.serializer.customSerializer : undefined, |
| 35 | + }); |
| 36 | + |
| 37 | + // Inject the new serializer into the Metro config |
| 38 | + config.serializer = { ...config.serializer, customSerializer: newSerializer }; |
| 39 | + |
| 40 | + return config; |
| 41 | +} |
| 42 | + |
| 43 | +function runServer() { |
| 44 | + const configFile = path.resolve( |
| 45 | + path.dirname(new URL(import.meta.url).pathname), |
| 46 | + "./tmp.js", |
| 47 | + ); |
| 48 | + const config = { ...discoveryrc, data: "tmp" }; |
| 49 | + |
| 50 | + fs.writeFileSync( |
| 51 | + configFile, |
| 52 | + `module.exports = ${JSON.stringify(config, null, 1).replace( |
| 53 | + '"tmp"', |
| 54 | + `() => require("${outputJsonPath}")`, |
| 55 | + )}`, |
| 56 | + ); |
| 57 | + |
| 58 | + createServer({ |
| 59 | + cache: false, |
| 60 | + minify: true, |
| 61 | + dev: false, |
| 62 | + config: configFile, |
| 63 | + configFile, |
| 64 | + }).then((server) => server.listen(8071)); |
| 65 | +} |
| 66 | + |
| 67 | +let isServerRunning = false; |
| 68 | + |
| 69 | +export async function withRozeniteBundleDiscoveryPlugin(config, options) { |
| 70 | + const metroConfig = await config; |
| 71 | + injectBundleDiscovery(metroConfig, options); |
| 72 | + |
| 73 | + if (!isServerRunning) { |
| 74 | + isServerRunning = true; |
| 75 | + runServer(); |
| 76 | + } |
| 77 | + |
| 78 | + return metroConfig; |
| 79 | +} |
0 commit comments