react-native-bundle-discovery-ui 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ const path = require("path");
2
+
3
+ module.exports = {
4
+ name: "react-native-bundle-discovery",
5
+ data: () => require("./tmp/metro-stats.json"),
6
+ setup: path.resolve(__dirname, "setup.js"),
7
+ view: {
8
+ assets: [
9
+ // Global styles
10
+ path.resolve(__dirname, "views/global.css"),
11
+ // Pages
12
+ path.resolve(__dirname, "pages/default.js"),
13
+ path.resolve(__dirname, "pages/module.js"),
14
+ path.resolve(__dirname, "pages/package.js"),
15
+ // Custom views
16
+ path.resolve(__dirname, "views/highcharts.css"),
17
+ path.resolve(__dirname, "views/prettify.js"),
18
+ path.resolve(__dirname, "views/highcharts.js"),
19
+ path.resolve(__dirname, "views/foamtree.js"),
20
+ ],
21
+ },
22
+ };
package/README.md ADDED
@@ -0,0 +1,161 @@
1
+ # react-native-bundle-discovery
2
+
3
+ [![react-native-bundle-discovery on npm](https://badgen.net/npm/v/react-native-bundle-discovery)](https://www.npmjs.com/package/react-native-bundle-discovery)
4
+ [![react-native-bundle-discovery downloads](https://badgen.net/npm/dm/react-native-bundle-discovery)](https://www.npmtrends.com/react-native-bundle-discovery)
5
+
6
+
7
+ A simple package that helps developers visualize and analyze the bundle size of React Native apps.
8
+ With this tool, you can easily explore your app's codebase, identify large or heavy packages, and inspect the structure of modules and code within your project.
9
+
10
+ <img width="800" alt="" src="./assets/img.png" />
11
+
12
+
13
+ ### What you should consider when analyzing your bundle
14
+
15
+ 1. if you use **React 19** then it's time to remove a `prop-types` package from your bundle.
16
+ 2. Search for `development|debug|dev|storybook` modules in your production JS bundle (it's a dead code that should not be there).
17
+ 3. Also check polyfills duplicates (search example: `url|fetch|crypto|buffer|base-?64`).
18
+ 4. Verify that you don't have any similar packages in your bundle (search example: `object|just-|debounce|ramda|lodash|underscore`). I often see that devs use both `lodash/debounce`, `lodash.debounce` and `debounce` in their projects. Or mix `ramda`, `underscore` and `lodash`._
19
+ 5. Try to find `package.json$` files in your bundle. They are often used to get only the package `version/name` but all other fields are not needed in the bundle.
20
+ 6. Please provide your ideas soo other devs can benefit from them :)
21
+
22
+
23
+ ### Setup:
24
+
25
+ There are two ways to install the package:
26
+
27
+ 1. As in independent tool
28
+ 2. Or as a [Rozenite](https://www.rozenite.dev/) plugin (see below).
29
+
30
+ #### 1. Install (independent tool)
31
+
32
+ ```bash
33
+ yarn add -D react-native-bundle-discovery react-native-bundle-discovery-ui
34
+ ```
35
+
36
+ Add to your `metro.config.js`:
37
+
38
+ ```diff
39
+ // metro.config.js
40
+ const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');
41
+ +const {createSerializer} = require('react-native-bundle-discovery');
42
+
43
+ +const mySerializer = createSerializer({
44
+ + includeCode: true, // Useful if you want to compare source/bundle code (but a report file will be larger)
45
+ + projectRoot: __dirname,
46
+ + //^^^ ⚠️ WARNING: In a monorepo setup, this should point to the monorepo root,
47
+ + // not the individual package directory.
48
+ +});
49
+
50
+ -const config = {};
51
+ +const config = {
52
+ + serializer: {
53
+ + customSerializer: mySerializer
54
+ + },
55
+ +};
56
+
57
+ module.exports = mergeConfig(getDefaultConfig(__dirname), config);
58
+ ```
59
+
60
+ ---
61
+
62
+ #### 2. Install as a Rozenite plugin (OPTIONAL)
63
+
64
+
65
+ ```bash
66
+ yarn dlx rozenite@latest init # init rozenite in your project (from: https://www.rozenite.dev/docs/getting-started)
67
+ yarn add -D react-native-bundle-discovery-rozenite-plugin # add the plugin to your project
68
+ ```
69
+
70
+ Then in the `metro.config.js` file add the following:
71
+
72
+ ```diff
73
+ const { withRozenite } = require('@rozenite/metro');
74
+ +const { withRozeniteBundleDiscoveryPlugin } = require('react-native-bundle-discovery-rozenite-plugin');
75
+ const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
76
+
77
+ /**
78
+ * Metro configuration
79
+ * https://reactnative.dev/docs/metro
80
+ *
81
+ * @type {import('@react-native/metro-config').MetroConfig}
82
+ */
83
+ const config = {};
84
+
85
+ module.exports = withRozenite(
86
+ mergeConfig(getDefaultConfig(__dirname), config),
87
+ {
88
+ + enhanceMetroConfig: config => withRozeniteBundleDiscoveryPlugin(config, { /* Your Bundle Discovery Options */ }),
89
+ enabled: true,
90
+ },
91
+ );
92
+ ```
93
+
94
+ Now you can run `yarn start` and open [React Native DevTools](https://reactnative.dev/docs/react-native-devtools)
95
+
96
+
97
+ ---
98
+
99
+
100
+ #### 3. Build the app
101
+
102
+ As example, for iOS you can run the following command, and it will generate the `metro-stats.json` file in the root of your project:
103
+
104
+ ```bash
105
+ npx react-native bundle \
106
+ --entry-file index.js \
107
+ --platform ios \
108
+ --dev false \
109
+ --bundle-output ios/main.jsbundle \
110
+ --assets-dest ios/assets
111
+ ```
112
+
113
+ #### 4. CLI
114
+
115
+ ##### 4.1 View the report in the browser
116
+
117
+ Run webserver to view the report:
118
+
119
+ ```bash
120
+ npx react-native-bundle-discovery-ui server metro-stats.json [--port <port>]
121
+ ```
122
+
123
+ ##### 4.2 Build the HTML report
124
+
125
+ Run the following command to generate an HTML report from the JSON file:
126
+
127
+ ```bash
128
+ npx react-native-bundle-discovery-ui build metro-stats.json
129
+ ```
130
+
131
+
132
+ ---
133
+
134
+ ### `createSerializer(options: Options)`
135
+
136
+ | Prop | Default value | Description |
137
+ | ---------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
138
+ | serializer: Function | Default serializer | A custom serializer function. If not provided, a default serializer is used. |
139
+ | projectRoot: string | Required | The root directory of the project. ⚠️ In a monorepo setup, this should point to the monorepo root, not the individual package directory. |
140
+ | outputJsonPath: string | `<root>/metro-stats.json` | The path where the JSON report will be saved. Defaults to `metro-stats.json` in project root. |
141
+ | includeCode: boolean | `true` | Whether to include the source and output code in the JSON report. |
142
+
143
+ ### Financial Contributors
144
+
145
+ Become a financial contributor at [OpenCollective](https://opencollective.com/react-native-bundle-discovery) or [GitHub Sponsors](https://github.com/sponsors/retyui)
146
+
147
+ ### Other
148
+
149
+ **Similar projects:**
150
+
151
+ - [expo-atlas](https://github.com/expo/atlas) [![expo-atlas downloads](https://badgen.net/npm/dm/expo-atlas)](https://www.npmtrends.com/expo-atlas) [![expo-atlas install size](https://packagephobia.com/badge?p=expo-atlas)](https://packagephobia.com/result?p=expo-atlas)
152
+ - [expo-atlas-without-expo](https://github.com/v3ron/expo-atlas-without-expo) [![expo-atlas-without-expo downloads](https://badgen.net/npm/dm/expo-atlas-without-expo)](https://www.npmtrends.com/expo-atlas-without-expo) [![expo-atlas-without-expo install size](https://packagephobia.com/badge?p=expo-atlas-without-expo)](https://packagephobia.com/result?p=expo-atlas-without-expo)
153
+ - [react-native-bundle-visualizer](https://github.com/callstack/react-native-bundle-visualizer) [![react-native-bundle-visualizer downloads](https://badgen.net/npm/dm/react-native-bundle-visualizer)](https://www.npmtrends.com/react-native-bundle-visualizer)[![react-native-bundle-visualizer install size](https://packagephobia.com/badge?p=react-native-bundle-visualizer)](https://packagephobia.com/result?p=react-native-bundle-visualizer)
154
+ - [webpack-bundle-analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer) [![webpack-bundle-analyzer downloads](https://badgen.net/npm/dm/webpack-bundle-analyzer)](https://www.npmtrends.com/webpack-bundle-analyzer)[![webpack-bundle-analyzer install size](https://packagephobia.com/badge?p=webpack-bundle-analyzer)](https://packagephobia.com/result?p=webpack-bundle-analyzer)
155
+ - [bundle-stats](https://github.com/relative-ci/bundle-stats/tree/master/packages/cli#readme) [![bundle-stats downloads](https://badgen.net/npm/dm/bundle-stats)](https://www.npmtrends.com/bundle-stats)[![bundle-stats install size](https://packagephobia.com/badge?p=bundle-stats)](https://packagephobia.com/result?p=bundle-stats)
156
+ - [statoscope](https://github.com/statoscope/statoscope) [![@statoscope/cli downloads](https://badgen.net/npm/dm/@statoscope/cli)](https://www.npmtrends.com/@statoscope/cli)[![@statoscope/cli install size](https://packagephobia.com/badge?p=@statoscope/cli)](https://packagephobia.com/result?p=@statoscope/cli)
157
+
158
+ **Built using [Discovery.js](https://github.com/discoveryjs/discovery):**
159
+
160
+ - Build blocks for pages: https://discoveryjs.github.io/discovery/#views-showcase
161
+ - Jora syntax: https://discoveryjs.github.io/jora/#article:jora-syntax-operators
package/index.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require("./lib/customSerializer");
package/lib/bin.js ADDED
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ const minimist = require("minimist");
3
+
4
+ function printHelp() {
5
+ console.log(`react-native-bundle-discovery
6
+
7
+ Usage:
8
+ react-native-bundle-discovery server <file> [port] [--verbose]
9
+ react-native-bundle-discovery build <file> [--output <path>] [--clean] [--single-file] [--verbose]
10
+
11
+ Commands:
12
+ server <file> [port] Run a web server to show a Metro bundler stat report
13
+ build <file> Build a HTML report from the Metro bundler stat file
14
+
15
+ Options:
16
+ -v, --verbose Run with verbose logging
17
+ -o, --output <path> Path for a build result (default: .bundle-discovery)
18
+ -c, --clean Clean output directory before writing build files (default: true)
19
+ -s, --single-file Output report build as a single HTML file (default: true)
20
+ -p, --port <port> Port for server command (same as [port], default: 8079)
21
+ -h, --help Show help
22
+ `);
23
+ }
24
+
25
+ function fail(message) {
26
+ console.error(message);
27
+ console.error("Use --help to see usage.");
28
+ process.exit(1);
29
+ }
30
+
31
+ const argv = minimist(process.argv.slice(2), {
32
+ alias: {
33
+ v: "verbose",
34
+ h: "help",
35
+ o: "output",
36
+ c: "clean",
37
+ s: "single-file",
38
+ p: "port",
39
+ },
40
+ boolean: ["verbose", "help", "clean", "single-file"],
41
+ string: ["output"],
42
+ default: {
43
+ clean: true,
44
+ "single-file": true,
45
+ },
46
+ });
47
+
48
+ const command = argv._[0];
49
+
50
+ if (argv.help || !command) {
51
+ printHelp();
52
+ process.exit(0);
53
+ }
54
+
55
+ if (command === "server") {
56
+ const file = argv._[1];
57
+ if (!file) {
58
+ fail("Missing required argument: <file>");
59
+ }
60
+
61
+ const rawPort = argv.port ?? argv._[2] ?? 8079;
62
+ const port = Number(rawPort);
63
+ if (!Number.isFinite(port)) {
64
+ fail(`Invalid port: ${rawPort}`);
65
+ }
66
+
67
+ const { serve } = require("./server.js");
68
+ return serve(file, port, Boolean(argv.verbose));
69
+ }
70
+
71
+ if (command === "build") {
72
+ const file = argv._[1];
73
+ if (!file) {
74
+ fail("Missing required argument: <file>");
75
+ }
76
+
77
+ const { buildHtmlPage } = require("./build.js");
78
+ return buildHtmlPage(
79
+ file,
80
+ argv.output,
81
+ argv.clean,
82
+ argv["single-file"],
83
+ Boolean(argv.verbose),
84
+ );
85
+ }
86
+
87
+ fail(`Unknown command: ${command}`);
package/lib/build.js ADDED
@@ -0,0 +1,115 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const chalk = require("chalk");
4
+ const { build } = require("@discoveryjs/cli");
5
+ const config = require("../.discoveryrc.js");
6
+
7
+ function buildHtmlPage(filePath, output, clean, singleFile, verbose) {
8
+ if (verbose) {
9
+ console.info(
10
+ `Building HTML page from file: ${chalk.green(filePath)} options: ${JSON.stringify(
11
+ { output, clean, singleFile },
12
+ null,
13
+ 2,
14
+ )}`,
15
+ );
16
+ }
17
+
18
+ if (!filePath) {
19
+ console.error(
20
+ `Usage: '${chalk.green("npx react-native-bundle-discovery build <path-to-file>")}', Please provide a path to a JSON file.`,
21
+ );
22
+ process.exit(1);
23
+ }
24
+
25
+ const jsonFilePath = path.resolve(process.cwd(), filePath);
26
+ if (verbose) {
27
+ console.info(
28
+ `Loading JSON file from: ${chalk.green(jsonFilePath)}, base directory: ${chalk.green(process.cwd())}`,
29
+ );
30
+ }
31
+
32
+ let fullJsonPath;
33
+
34
+ try {
35
+ fullJsonPath = require.resolve(jsonFilePath);
36
+ } catch (err) {
37
+ console.error(`❌Error loading file: ${chalk.red(jsonFilePath)}\n\n`);
38
+ console.error(err.message);
39
+ process.exit(1);
40
+ }
41
+
42
+ const configFile = path.resolve(__dirname, "./.tmp.js");
43
+
44
+ if (verbose) {
45
+ console.info(
46
+ `Creating temporary config file at: ${chalk.green(configFile)}, for discovery.js`,
47
+ );
48
+ }
49
+ fs.writeFileSync(
50
+ configFile,
51
+ `module.exports = ${JSON.stringify(
52
+ { ...config, data: "<tmp>" },
53
+ null,
54
+ 1,
55
+ ).replace(`"<tmp>"`, `() => require("${fullJsonPath}")`)};`,
56
+ );
57
+
58
+ if (verbose) {
59
+ console.info(`Building HTML page with options:`, {
60
+ output,
61
+ clean,
62
+ singleFile,
63
+ });
64
+ }
65
+
66
+ const _config = {
67
+ name: "Bundle Discovery",
68
+ mode: "single",
69
+ // models: [ [Object] ],
70
+ colorScheme: "auto",
71
+ download: true,
72
+ upload: false,
73
+ embed: false,
74
+ encodings: false,
75
+ };
76
+ const _options = {
77
+ singleFile,
78
+ clean,
79
+ output,
80
+ //
81
+ cache: true,
82
+ cachedir: path.resolve(__dirname, "./.discoveryjs-cache"),
83
+ checkCacheTtl: false,
84
+ minify: true,
85
+ dataCompression: true,
86
+ sourcemap: false,
87
+ embed: "by-config",
88
+ experimentalJsonxl: false,
89
+ scriptFormat: "esm",
90
+ scriptExternal: [],
91
+ data: true,
92
+ excludeModelOnDataFail: false,
93
+ prettyData: false,
94
+ modelDownload: false,
95
+ modelDataUpload: true,
96
+ modelResetCache: false,
97
+ serveOnlyAssets: true,
98
+ dev: true,
99
+ config: configFile,
100
+ configFile: configFile,
101
+ };
102
+ return build(_options, _config, configFile).then((result) => {
103
+ console.log(`========================================`);
104
+ console.log(
105
+ `✅ HTML page built successfully at: ${chalk.green(
106
+ path.resolve(output, "index.html").replace(process.cwd() + "/", ""),
107
+ )}`,
108
+ );
109
+ console.log(`========================================`);
110
+ });
111
+ }
112
+
113
+ module.exports = {
114
+ buildHtmlPage,
115
+ };
package/lib/server.js ADDED
@@ -0,0 +1,82 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const chalk = require("chalk");
4
+ const { createServer } = require("@discoveryjs/cli");
5
+ const { silent } = require("@discoveryjs/cli/lib/shared/utils.js");
6
+ const config = require("../.discoveryrc.js");
7
+
8
+ function serve(filePath, port, verbose) {
9
+ const PORT = process.env.PORT || port;
10
+
11
+ if (verbose) {
12
+ console.info(
13
+ `start server with file: ${filePath} on port: ${port} ${process.env.PORT ? `(${chalk.yellow("PORT")} env)` : ""}`,
14
+ );
15
+ }
16
+
17
+ if (!filePath) {
18
+ console.error(
19
+ `Usage: '${chalk.green("npx react-native-bundle-discovery server <path-to-file>")}', Please provide a path to a JSON file.`,
20
+ );
21
+ process.exit(1);
22
+ }
23
+
24
+ const jsonFilePath = path.resolve(process.cwd(), filePath);
25
+ if (verbose) {
26
+ console.info(
27
+ `Loading JSON file from: ${chalk.green(jsonFilePath)}, base directory: ${chalk.green(process.cwd())}`,
28
+ );
29
+ }
30
+
31
+ let fullJsonPath;
32
+
33
+ try {
34
+ fullJsonPath = require.resolve(jsonFilePath);
35
+ } catch (err) {
36
+ console.error(`❌Error loading file: ${chalk.red(jsonFilePath)}\n\n`);
37
+ console.error(err.message);
38
+ process.exit(1);
39
+ }
40
+
41
+ const configFile = path.resolve(__dirname, "./.tmp.js");
42
+
43
+ if (verbose) {
44
+ console.info(
45
+ `Creating temporary config file at: ${chalk.green(configFile)}, for discovery.js`,
46
+ );
47
+ }
48
+ fs.writeFileSync(
49
+ configFile,
50
+ `module.exports = ${JSON.stringify(
51
+ { ...config, data: "<tmp>" },
52
+ null,
53
+ 1,
54
+ ).replace(`"<tmp>"`, `() => require("${fullJsonPath}")`)};`,
55
+ );
56
+
57
+ if (verbose) {
58
+ console.info(`Running server with config: ${chalk.green(configFile)}`);
59
+ }
60
+
61
+ return silent(() =>
62
+ createServer({
63
+ cache: false,
64
+ minify: true,
65
+ dev: false,
66
+ config: configFile,
67
+ configFile,
68
+ }).then((server) =>
69
+ server.listen(PORT, () => {
70
+ console.log(
71
+ `[react-native-bundle-discovery]: 🚀 Server listen on ${chalk.green.underline(
72
+ chalk.green(`http://localhost:${PORT}`),
73
+ )}`,
74
+ );
75
+ }),
76
+ ),
77
+ );
78
+ }
79
+
80
+ module.exports = {
81
+ serve,
82
+ };
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "react-native-bundle-discovery-ui",
3
+ "version": "2.0.0-rc.1",
4
+ "main": "index.js",
5
+ "bin": "lib/bin.js",
6
+ "repository": "git@github.com:retyui/react-native-bundle-discovery.git",
7
+ "author": "David <4661784+retyui@users.noreply.github.com>",
8
+ "license": "MIT",
9
+ "scripts": {
10
+ "format": "prettier --write .",
11
+ "start": "NODE_ENV=development npx discovery --config .discoveryrc.js",
12
+ "build": "npx discovery-build --config .discoveryrc.js --output build --serve-only-assets --single-file"
13
+ },
14
+ "dependencies": {
15
+ "@discoveryjs/cli": "2.14.7",
16
+ "@discoveryjs/discovery": "1.0.0-beta.99",
17
+ "chalk": "^4.1.2",
18
+ "minimist": "^1.2.8",
19
+ "prettier": "^3.8.1"
20
+ },
21
+ "peerDependencies": {
22
+ "metro": "*"
23
+ },
24
+ "peerDependenciesMeta": {
25
+ "metro": {
26
+ "optional": true
27
+ }
28
+ },
29
+ "files": [
30
+ "vendors",
31
+ "lib",
32
+ "views",
33
+ "pages",
34
+ "index.js",
35
+ "setup.js",
36
+ "prepare.js",
37
+ "queryHelpers.js",
38
+ ".discoveryrc.js"
39
+ ],
40
+ "packageManager": "yarn@4.13.0"
41
+ }