react-native-bundle-discovery 1.1.0 → 1.2.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.
package/README.md CHANGED
@@ -9,7 +9,7 @@ With this tool, you can easily explore your app's codebase, identify large or he
9
9
  ### What you should consider when analyzing your bundle
10
10
 
11
11
  1. if you use **React 19** then it's time to remove a `prop-types` package from your bundle.
12
- 2. Search for `development|debug|dev` modules in your production JS bundle (it's a dead code that should not be there).
12
+ 2. Search for `development|debug|dev|storybook` modules in your production JS bundle (it's a dead code that should not be there).
13
13
  3. Also check polyfills duplicates (search example: `url|fetch|crypto|buffer|base-?64`).
14
14
  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`._
15
15
  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.
@@ -18,13 +18,18 @@ With this tool, you can easily explore your app's codebase, identify large or he
18
18
 
19
19
  ### Setup:
20
20
 
21
- #### 1. Install
21
+ There are two ways to install the package:
22
+
23
+ 1. As in independent tool
24
+ 2. Or as a [Rozenite](https://www.rozenite.dev/) plugin (see below).
25
+
26
+ #### 1. Install (independent tool)
22
27
 
23
28
  ```bash
24
29
  yarn add -D react-native-bundle-discovery
25
30
  ```
26
31
 
27
- #### 2. Add to your metro.config.js
32
+ Add to your `metro.config.js`:
28
33
 
29
34
  ```diff
30
35
  // metro.config.js
@@ -48,6 +53,46 @@ const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');
48
53
  module.exports = mergeConfig(getDefaultConfig(__dirname), config);
49
54
  ```
50
55
 
56
+ ---
57
+
58
+ #### 2. Install as a Rozenite plugin (OPTIONAL)
59
+
60
+
61
+ ```bash
62
+ yarn dlx rozenite@latest init # init rozenite in your project (from: https://www.rozenite.dev/docs/getting-started)
63
+ yarn add -D react-native-bundle-discovery-rozenite-plugin # add the plugin to your project
64
+ ```
65
+
66
+ Then in the `metro.config.js` file add the following:
67
+
68
+ ```diff
69
+ const { withRozenite } = require('@rozenite/metro');
70
+ +const { withRozeniteBundleDiscoveryPlugin } = require('react-native-bundle-discovery-rozenite-plugin');
71
+ const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
72
+
73
+ /**
74
+ * Metro configuration
75
+ * https://reactnative.dev/docs/metro
76
+ *
77
+ * @type {import('@react-native/metro-config').MetroConfig}
78
+ */
79
+ const config = {};
80
+
81
+ module.exports = withRozenite(
82
+ mergeConfig(getDefaultConfig(__dirname), config),
83
+ {
84
+ + enhanceMetroConfig: config => withRozeniteBundleDiscoveryPlugin(config, { /* Your Bundle Discovery Options */ }),
85
+ enabled: true,
86
+ },
87
+ );
88
+ ```
89
+
90
+ Now you can run `yarn start` and open [React Native DevTools](https://reactnative.dev/docs/react-native-devtools)
91
+
92
+
93
+ ---
94
+
95
+
51
96
  #### 3. Build the app
52
97
 
53
98
  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:
@@ -61,14 +106,25 @@ npx react-native bundle \
61
106
  --assets-dest ios/assets
62
107
  ```
63
108
 
64
- #### 4. View the report
109
+ #### 4. CLI
110
+
111
+ ##### 4.1 View the report in the browser
65
112
 
66
113
  Run webserver to view the report:
67
114
 
68
115
  ```bash
69
- npx react-native-bundle-discovery metro-stats.json
116
+ npx react-native-bundle-discovery server metro-stats.json [--port <port>]
70
117
  ```
71
118
 
119
+ ##### 4.2 Build the HTML report
120
+
121
+ Run the following command to generate an HTML report from the JSON file:
122
+
123
+ ```bash
124
+ npx react-native-bundle-discovery build metro-stats.json
125
+ ```
126
+
127
+
72
128
  ---
73
129
 
74
130
  ### `createSerializer(optiosn: Options)`
@@ -93,7 +149,7 @@ Become a financial contributor at [OpenCollective](https://opencollective.com/re
93
149
  - https://github.com/callstack/react-native-bundle-visualizer
94
150
  - https://github.com/webpack-contrib/webpack-bundle-analyzer
95
151
  - https://github.com/statoscope/statoscope
96
- - https://github.com/relative-ci/bundle-stats/tree/master/packages/cli
152
+ - [https://github.com/relative-ci/bundle-stats/tree/master/packages/cli](https://github.com/relative-ci/bundle-stats/tree/master/packages/cli#readme)
97
153
 
98
154
  **Built using [Discovery.js](https://github.com/discoveryjs/discovery):**
99
155
 
package/lib/.tmp.js ADDED
@@ -0,0 +1,17 @@
1
+ module.exports = {
2
+ "name": "react-native-bundle-discovery",
3
+ "data": () => require("/Users/davyd.narbutovich/open-source/bundle-discovery/tmp/dtv-metro-stats.json"),
4
+ "setup": "/Users/davyd.narbutovich/open-source/bundle-discovery/setup.js",
5
+ "view": {
6
+ "assets": [
7
+ "/Users/davyd.narbutovich/open-source/bundle-discovery/views/global.css",
8
+ "/Users/davyd.narbutovich/open-source/bundle-discovery/pages/default.js",
9
+ "/Users/davyd.narbutovich/open-source/bundle-discovery/pages/module.js",
10
+ "/Users/davyd.narbutovich/open-source/bundle-discovery/pages/package.js",
11
+ "/Users/davyd.narbutovich/open-source/bundle-discovery/views/highcharts.css",
12
+ "/Users/davyd.narbutovich/open-source/bundle-discovery/views/prettify.js",
13
+ "/Users/davyd.narbutovich/open-source/bundle-discovery/views/highcharts.js",
14
+ "/Users/davyd.narbutovich/open-source/bundle-discovery/views/foamtree.js"
15
+ ]
16
+ }
17
+ };
package/lib/bin.js CHANGED
@@ -1,52 +1,74 @@
1
1
  #!/usr/bin/env node
2
- const fs = require("fs");
3
- const path = require("path");
4
- const chalk = require("chalk");
5
- const { createServer } = require("@discoveryjs/cli");
6
- const config = require("../.discoveryrc.js");
2
+ const yargs = require("yargs");
3
+ const { hideBin } = require("yargs/helpers");
7
4
 
8
- const filePath = process.argv[2];
9
-
10
- if (!filePath) {
11
- console.error(
12
- `Usage: '${chalk.green("npx react-native-bundle-discovery <path-to-file>")}', Please provide a path to a JSON file.`,
13
- );
14
- process.exit(1);
15
- }
16
-
17
- const jsonFilePath = path.resolve(process.cwd(), filePath);
18
-
19
- let fullJsonPath;
20
-
21
- try {
22
- fullJsonPath = require.resolve(jsonFilePath);
23
- } catch (err) {
24
- console.error(`Error loading file: ${chalk.red(jsonFilePath)}`);
25
- console.error(err.message);
26
- process.exit(1);
27
- }
28
-
29
- const PORT = process.env.PORT || 8079;
30
-
31
- const configFile = path.resolve(__dirname, "./.tmp.js");
32
-
33
- fs.writeFileSync(
34
- configFile,
35
- `module.exports = ${JSON.stringify(
36
- { ...config, data: "<tmp>" },
37
- null,
38
- 1,
39
- ).replace(`"<tmp>"`, `() => require("${fullJsonPath}")`)};`,
40
- );
41
-
42
- createServer({
43
- cache: false,
44
- minify: true,
45
- dev: false,
46
- config: configFile,
47
- configFile,
48
- }).then((server) =>
49
- server.listen(PORT, () =>
50
- console.log(`Server listen on ${chalk.green(`http://localhost:${PORT}`)}`),
51
- ),
52
- );
5
+ yargs(hideBin(process.argv))
6
+ .command(
7
+ "server <file> [port]",
8
+ "🚀 Run a web server to show a Metro bundler stat report",
9
+ (yargs) => {
10
+ return yargs
11
+ .positional("file", {
12
+ describe: "Path to the Metro bundler report json file",
13
+ type: "string",
14
+ demandOption: true,
15
+ })
16
+ .positional("port", {
17
+ describe:
18
+ "🔌 Port to start the server on (also can be set with PORT env. var.)",
19
+ type: "number",
20
+ default: 8079,
21
+ });
22
+ },
23
+ (argv) => {
24
+ const { serve } = require("./server.js");
25
+ serve(argv.file, argv.port, argv.verbose);
26
+ },
27
+ )
28
+ .command(
29
+ "build <file>",
30
+ "📦 Build a HTML report from the Metro bundler stat file",
31
+ (yargs) => {
32
+ return yargs
33
+ .positional("file", {
34
+ describe: "Path to the Metro bundler report json file",
35
+ type: "string",
36
+ demandOption: true,
37
+ })
38
+ .option("output", {
39
+ alias: "o",
40
+ describe: "Path for a build result",
41
+ type: "string",
42
+ default: ".bundle-discovery",
43
+ })
44
+ .option("clean", {
45
+ alias: "c",
46
+ describe: "Clean the output directory before emit a build files",
47
+ type: "boolean",
48
+ default: true,
49
+ })
50
+ .option("single-file", {
51
+ alias: "s",
52
+ describe: "Output a report build as a single HTML file",
53
+ type: "boolean",
54
+ default: true,
55
+ });
56
+ },
57
+ (argv) => {
58
+ const { buildHtmlPage } = require("./build.js");
59
+ buildHtmlPage(
60
+ argv.file,
61
+ argv.output,
62
+ argv.clean,
63
+ argv.singleFile,
64
+ argv.verbose,
65
+ );
66
+ },
67
+ )
68
+ .option("verbose", {
69
+ alias: "v",
70
+ type: "boolean",
71
+ description: "Run with verbose logging",
72
+ })
73
+ .help()
74
+ .parse();
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
+ 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
+ };
@@ -94,6 +94,7 @@ function createJsonReport({
94
94
  includeCode,
95
95
  outputJsonPath,
96
96
  rootFolder,
97
+ silent,
97
98
  }) {
98
99
  const dependencies = Array.from(graph.dependencies.values());
99
100
 
@@ -114,9 +115,11 @@ function createJsonReport({
114
115
 
115
116
  writeFileSync(outputJsonPath, JSON.stringify(stats));
116
117
 
117
- console.log(
118
- `${chalk.yellow(`[${NAME}]`)}: Saved stats to ${chalk.green(outputJsonPath)}`,
119
- );
118
+ if (!silent) {
119
+ console.log(
120
+ `${chalk.yellow(`[${NAME}]`)}: Saved stats to ${chalk.green(outputJsonPath)}`,
121
+ );
122
+ }
120
123
  }
121
124
 
122
125
  /**
@@ -137,6 +140,7 @@ function createSerializer({
137
140
  projectRoot,
138
141
  outputJsonPath,
139
142
  includeCode = true,
143
+ silent = false,
140
144
  includeEnvs = [],
141
145
  } = {}) {
142
146
  const mySerializer = serializer || getDefaultSerializer();
@@ -159,6 +163,7 @@ function createSerializer({
159
163
  includeCode,
160
164
  outputJsonPath: myOutputJsonPath,
161
165
  rootFolder: projectRoot,
166
+ silent,
162
167
  });
163
168
 
164
169
  return code;
package/lib/server.js ADDED
@@ -0,0 +1,81 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const chalk = require("chalk");
4
+ const { createServer } = require("@discoveryjs/cli");
5
+ const config = require("../.discoveryrc.js");
6
+
7
+ function serve(filePath, port, verbose) {
8
+ const PORT = process.env.PORT || port;
9
+
10
+ if (verbose) {
11
+ console.info(
12
+ `start server with file: ${filePath} on port: ${port} ${process.env.PORT ? `(${chalk.yellow("PORT")} env)` : ""}`,
13
+ );
14
+ }
15
+
16
+ if (!filePath) {
17
+ console.error(
18
+ `Usage: '${chalk.green("npx react-native-bundle-discovery server <path-to-file>")}', Please provide a path to a JSON file.`,
19
+ );
20
+ process.exit(1);
21
+ }
22
+
23
+ const jsonFilePath = path.resolve(process.cwd(), filePath);
24
+ if (verbose) {
25
+ console.info(
26
+ `Loading JSON file from: ${chalk.green(jsonFilePath)}, base directory: ${chalk.green(process.cwd())}`,
27
+ );
28
+ }
29
+
30
+ let fullJsonPath;
31
+
32
+ try {
33
+ fullJsonPath = require.resolve(jsonFilePath);
34
+ } catch (err) {
35
+ console.error(`❌Error loading file: ${chalk.red(jsonFilePath)}\n\n`);
36
+ console.error(err.message);
37
+ process.exit(1);
38
+ }
39
+
40
+ const configFile = path.resolve(__dirname, "./.tmp.js");
41
+
42
+ if (verbose) {
43
+ console.info(
44
+ `Creating temporary config file at: ${chalk.green(configFile)}, for discovery.js`,
45
+ );
46
+ }
47
+ fs.writeFileSync(
48
+ configFile,
49
+ `module.exports = ${JSON.stringify(
50
+ { ...config, data: "<tmp>" },
51
+ null,
52
+ 1,
53
+ ).replace(`"<tmp>"`, `() => require("${fullJsonPath}")`)};`,
54
+ );
55
+
56
+ if (verbose) {
57
+ console.info(`Running server with config: ${chalk.green(configFile)}`);
58
+ }
59
+
60
+ createServer({
61
+ cache: false,
62
+ minify: true,
63
+ dev: false,
64
+ config: configFile,
65
+ configFile,
66
+ }).then((server) =>
67
+ server.listen(PORT, () => {
68
+ console.log(`========================================`);
69
+ console.log(
70
+ `🚀 Server listen on ${chalk.green.underline(
71
+ chalk.green(`http://localhost:${PORT}`),
72
+ )}`,
73
+ );
74
+ console.log(`========================================`);
75
+ }),
76
+ );
77
+ }
78
+
79
+ module.exports = {
80
+ serve,
81
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-bundle-discovery",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "main": "index.js",
5
5
  "bin": "lib/bin.js",
6
6
  "repository": "git@github.com:retyui/react-native-bundle-discovery.git",
@@ -17,7 +17,8 @@
17
17
  "@discoveryjs/discovery": "1.0.0-beta.93",
18
18
  "chalk": "^4.1.2",
19
19
  "highcharts": "12.2.0",
20
- "prettier": "^3.5.3"
20
+ "prettier": "^3.5.3",
21
+ "yargs": "^17.7.2"
21
22
  },
22
23
  "peerDependencies": {
23
24
  "metro": "*"
package/pages/package.js CHANGED
@@ -98,6 +98,17 @@ discovery.page.define("package", {
98
98
  `html: '<span class="my-icon-inline my-icon-12">${externalLinkHtml}</span>'`,
99
99
  ],
100
100
  },
101
+ {
102
+ view: "link",
103
+ external: true,
104
+ data: `{ href: "https://bundlejs.com/?q=" + currentPkgWithUniqVer, q: currentPkgWithUniqVer }`,
105
+ content: [
106
+ {
107
+ view: "html",
108
+ data: `'<img class="bundlejs-badge-img" src="https://deno.bundlejs.com/?q=' + q + '&badge=detailed" />'`,
109
+ },
110
+ ],
111
+ },
101
112
  ],
102
113
  },
103
114
 
package/views/global.css CHANGED
@@ -162,3 +162,8 @@ hr{
162
162
  margin-top: 12px;
163
163
  height: 35px;
164
164
  }
165
+ .bundlejs-badge-img{
166
+ line-height: 0;
167
+ margin-bottom: -5px;
168
+ margin-left: 10px;
169
+ }