### Install react-native-startup-time Package
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/recipes/capturing-startup-time
Installs the 'react-native-startup-time' package, a third-party library required for capturing application startup performance metrics. This package may require manual linking for older React Native versions (<= 0.60).
```bash
yarn add react-native-startup-time
# or with npm
# npm install react-native-startup-time --save
```
--------------------------------
### Install and Configure visualize-bundle
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/recipes/bundle-analysis
Installs the 'visualize-bundle' development dependency and adds a script to package.json for running bundle analysis. This helps in understanding bundle size and identifying optimization opportunities.
```bash
yarn add visualize-bundle --dev
# or with npm
# npm install visualize-bundle --save-dev
```
```json
{
"scripts": {
"bundle:analysis": "visualize-bundle"
}
}
```
--------------------------------
### Run React Native Bundle Analyzer
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/next/recipes/bundle-analysis
Commands to start the React Native packager and run the bundle analysis script in separate terminals.
```bash
# In one terminal:
react-native start
# In the second terminal:
yarn run bundle:analysis
# or with npm
# npm run bundle:analysis
```
--------------------------------
### Install visualize-bundle
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/next/recipes/bundle-analysis
Installs the visualize-bundle package as a development dependency for bundle analysis.
```bash
yarn add visualize-bundle --dev
# or with npm
# npm install visualize-bundle --save-dev
```
--------------------------------
### Install React Native Bundle Splitter using Yarn or npm
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/fundamentals/getting-started
This snippet demonstrates how to add the 'react-native-bundle-splitter' package to your project using either the Yarn package manager or npm. It's a direct dependency installation for integrating the bundle splitting functionality.
```bash
yarn add react-native-bundle-splitter
```
```bash
npm install react-native-bundle-splitter --save
```
--------------------------------
### Run Bundle Analysis Commands (Shell)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/recipes/bundle-analysis
Commands to start the React Native packager and then run the bundle analysis script. This process generates a visual representation of your bundle, helping to identify large dependencies.
```shell
react-native start
```
```shell
yarn run bundle:analysis
```
```shell
npm run bundle:analysis
```
--------------------------------
### Install Babel Plugin for Jest Tests
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/recipes/jest-testing-guide
Installs the `babel-plugin-dynamic-import-node` as a development dependency, which is required for Jest to correctly process dynamic import statements within the Node.js runtime.
```shell
yarn add babel-plugin-dynamic-import-node --dev
```
```shell
npm install babel-plugin-dynamic-import-node --save-dev
```
--------------------------------
### Investigate Startup Modules (JavaScript)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/guides/metro
A JavaScript utility to identify modules loaded on initial app start. This code should be placed in `App.js`. It uses the `investigate` function from `react-native-bundle-splitter/dist/utils` and logs the sorted list of loaded modules.
```javascript
+import { investigate } from 'react-native-bundle-splitter/dist/utils';
+console.log(`module.exports = ${JSON.stringify(investigate().loaded.sort())};`);
```
--------------------------------
### React Navigation Integration: App Container Setup
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/guides/navigation
Sets up the main App container for a React Native application using `react-navigation`. This file remains unchanged when integrating bundle splitting.
```typescript
import React from 'react';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import { AppNavigator } from './navigator';
const AppContainer = createAppContainer(AppNavigator);
export default class App extends React.Component {
render() {
return ;
}
}
```
--------------------------------
### Install visualize-bundle for Bundle Analysis (Yarn/NPM)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/recipes/bundle-analysis
Installs the 'visualize-bundle' package as a development dependency. This tool aids in analyzing and visualizing the contents of your React Native application bundle to identify large modules.
```shell
yarn add visualize-bundle --dev
```
```shell
npm install visualize-bundle --save-dev
```
--------------------------------
### Investigate Initial App Load Modules (JavaScript)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/guides/metro
This JavaScript snippet, intended for `App.js`, uses the `investigate` utility from `react-native-bundle-splitter` to identify modules loaded on initial app start. It logs a JSON string of sorted loaded modules, which is then used to create platform-specific module files.
```javascript
+import { investigate } from 'react-native-bundle-splitter/dist/utils';
+console.log(`module.exports = ${JSON.stringify(investigate().loaded.sort())};`);
```
--------------------------------
### React Navigation Integration: Before and After Bundle Splitting
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/next/guides/navigation
Demonstrates how to integrate React Native Bundle Splitter with react-navigation. The 'Before' snippet shows the standard stack navigator setup, while the 'After' snippet shows how to use the `register` function from react-native-bundle-splitter to lazy load screens.
```typescript
import { createStackNavigator } from 'react-navigation';
import DetailsScreen from './details';
import HomeScreen from './home';
export const AppNavigator = createStackNavigator(
{
'Home': HomeScreen,
'Details': DetailsScreen
},
{
initialRouteName: 'Home'
}
);
```
```typescript
import { createStackNavigator } from 'react-navigation';
import { register } from 'react-native-bundle-splitter';
export const AppNavigator = createStackNavigator(
{
'Home': register({ loader: () => import('./home') }),
'Details': register({ loader: () => import('./details') })
},
{
initialRouteName: 'Home'
}
);
```
--------------------------------
### Configure Babel for Jest with dynamic-import-node
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/next/recipes/jest-testing-guide
Adds the 'dynamic-import-node' Babel plugin to the configuration for the 'test' environment. This ensures that dynamic imports are correctly handled by Jest, preventing issues where Jest might alter the structure of imported modules.
```javascript
// For babel.config.js
if (process.env.NODE_ENV === "test") {
config.plugins.push("dynamic-import-node");
}
```
```json
{
"presets": ... ,
"plugins": [
...
],
"env": {
"test": {
"plugins": ["dynamic-import-node"]
}
}
}
```
--------------------------------
### Investigate Bundle Performance with React Native Bundle Splitter
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/fundamentals/basic-usage
This snippet illustrates how to use the `investigate` utility from `react-native-bundle-splitter/dist/utils` to check the performance metrics of your application's bundle. By calling `investigate()` and logging its output, you can observe the number of loaded and waiting files. This information is crucial for understanding the impact of code splitting and optimizing the startup time of your React Native application. The expected output format is an object like `{ loaded: number, waiting: number }`.
```javascript
import React, { Fragment, PureComponent } from 'react';
import { investigate } from 'react-native-bundle-splitter/dist/utils';
console.log('Bundle Info: ', investigate());
class App extends PureComponent {
// ... component logic
}
```
--------------------------------
### Investigate Startup Modules for React Native Bundle Splitter
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/guides/metro
This utility function helps identify modules to be included in the 'startup' bundle. It should be added to your `App.js` file. The output, a JSON string of sorted loaded module paths, should be saved to platform-specific files (`modules.ios.js` or `modules.android.js`).
```javascript
import { investigate } from 'react-native-bundle-splitter/dist/utils';
console.log(`module.exports = ${JSON.stringify(investigate().loaded.sort())};`);
```
--------------------------------
### React Navigation Integration: Route Declaration (Before)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/guides/navigation
Example of a route declaration for React Navigation before integrating with React Native Bundle Splitter. Screens are imported directly.
```typescript
import { createStackNavigator } from 'react-navigation';
import DetailsScreen from './details';
import HomeScreen from './home';
export const AppNavigator = createStackNavigator(
{
'Home': HomeScreen,
'Details': DetailsScreen
},
{
initialRouteName: 'Home'
}
);
```
--------------------------------
### React Native Navigation Integration: Route Declaration (Before)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/guides/navigation
Example of registering components with React Native Navigation before integrating with React Native Bundle Splitter. Screens are registered directly.
```typescript
import { Navigation } from 'react-native-navigation';
import DetailsScreen from './details';
import HomeScreen from './home';
Navigation.registerComponent('Home', () => HomeScreen);
Navigation.registerComponent('Details', () => DetailsScreen);
```
--------------------------------
### Investigate Bundle Performance Metrics in React Native
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/next/fundamentals/basic-usage
This snippet illustrates how to use the `investigate` utility from 'react-native-bundle-splitter' to log bundle performance metrics to the console. This helps in understanding the impact of lazy loading on application startup time.
```javascript
import React, { Fragment, PureComponent } from 'react';
import { investigate } from 'react-native-bundle-splitter/dist/utils';
console.log('Bundle Info: ', investigate());
class App extends PureComponent {
// ... rest of your App component
```
--------------------------------
### React Native Component Without Static Navigation Options
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/guides/static-options
Example of a React Native component where `navigationOptions` are no longer defined within the class itself. This is because they are now managed externally via the `register` function in the context of `react-native-bundle-splitter`.
```javascript
class HomeScreen extends React.Component {
// navigationOptions are removed - now they are in register function
/* render function, etc */
}
```
--------------------------------
### Investigate Bundle Performance with React Native Bundle Splitter
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/fundamentals/basic-usage
This code snippet shows how to integrate the `investigate` utility from 'react-native-bundle-splitter/dist/utils' into your `App.js` file. It logs metrics about loaded and waiting modules, allowing you to monitor the impact of code splitting on your application's startup performance.
```javascript
import React, { Fragment, PureComponent } from 'react';
import { investigate } from 'react-native-bundle-splitter/dist/utils';
console.log('Bundle Info: ', investigate());
class App extends PureComponent {
// ... other component code
}
```
--------------------------------
### Configure Babel for Jest with dynamic-import-node (.babelrc)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/recipes/jest-testing-guide
Configures the `dynamic-import-node` Babel plugin specifically for the 'test' environment within a `.babelrc` file. This approach isolates the plugin's effect to Jest runs, preventing interference with other build environments.
```json
{
"presets": ... ,
"plugins": [
...
],
"env": {
"test": {
"plugins": ["dynamic-import-node"]
}
}
}
```
--------------------------------
### Run Bundle Analysis
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/recipes/bundle-analysis
Commands to run the React Native development server and the bundle analysis tool concurrently. This process generates a visual representation of the application bundle, aiding in size analysis.
```bash
react-native start
```
```bash
yarn run bundle:analysis
# or with npm
# npm run bundle:analysis
```
--------------------------------
### Configure Babel for Jest with dynamic-import-node (babel.config.js)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/recipes/jest-testing-guide
Adds the `dynamic-import-node` Babel plugin conditionally to the configuration when the `NODE_ENV` is set to 'test'. This ensures the plugin is only active during Jest test execution, resolving issues with dynamic imports that Jest might otherwise mishandle.
```javascript
if (process.env.NODE_ENV === "test") {
config.plugins.push("dynamic-import-node");
}
```
--------------------------------
### Add StartupTime Component to Application Root
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/next/recipes/capturing-startup-time
Integrates the `StartupTime` component into the root of your React Native application. This JSX element will render and capture startup time metrics. An optional `style` prop can be applied for custom styling.
```jsx
```
--------------------------------
### Basic Architecture: DetailsScreen Component (TypeScript)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/guides/navigation
Defines a basic DetailsScreen component using React Native. It includes a Text element and a Button to navigate back to the 'Home' screen. The `goToHome` method is a placeholder for navigation logic.
```typescript
import React from 'react';
import { Button, View, Text } from 'react-native';
class DetailsScreen extends React.Component {
render() {
return (
Details Screen
);
}
private goToHome = () => {
// call specific function to perform navigation
// in case of `react-navigation`: this.props.navigation.navigate('Home')
// see routes definition below for each library
}
}
```
--------------------------------
### Enable RAM Bundle on Android (Gradle)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/fundamentals/enabling-ram-bundle
Configure the `android/app/build.gradle` file to enable RAM Bundle format for your React Native application on Android. This involves adding specific properties to the `react` extension to specify the bundle command and extra packager arguments for an indexed RAM bundle.
```gradle
project.ext.react = [
entryFile : "index.js",
+ bundleCommand : "ram-bundle",
+ extraPackagerArgs : ["--indexed-ram-bundle"]
]
...
```
--------------------------------
### Investigate Bundle Performance with React Native Bundle Splitter
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/fundamentals/basic-usage
This snippet illustrates how to use the `investigate` utility from `react-native-bundle-splitter/dist/utils` to log bundle performance metrics. By calling `investigate()` and logging its output, developers can monitor the number of loaded and waiting modules, helping to optimize bundle sizes and startup times.
```javascript
import React, { Fragment, PureComponent } from 'react';
import { investigate } from 'react-native-bundle-splitter/dist/utils';
console.log('Bundle Info: ', investigate());
class App extends PureComponent {
// ... rest of your App component
}
```
--------------------------------
### Integrate StartupTime Component in React Native App
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/recipes/capturing-startup-time
Renders the 'StartupTime' component within the root of your React Native application. This component is used to visually display or capture the application's startup time. An optional 'style' prop can be provided for customization.
```jsx
```
--------------------------------
### Define Static Navigation Options in React Native Component
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/guides/static-options
Demonstrates how to define static `navigationOptions` within a React Native `PureComponent` class for screen configuration. This is the standard approach before considering bundle splitting.
```javascript
class HomeScreen extends React.PureComponent {
static navigationOptions = {
title: 'Home',
};
/* render function, etc */
}
```
--------------------------------
### Enable RAM Bundle for Android
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/fundamentals/enabling-ram-bundle
Configure the `android/app/build.gradle` file to enable the RAM Bundle format for Android. This involves setting `bundleCommand` to 'ram-bundle' and optionally `extraPackagerArgs` for indexed format.
```gradle
project.ext.react = [
entryFile : "index.js",
bundleCommand : "ram-bundle",
extraPackagerArgs : ["--indexed-ram-bundle"]
]...
```
--------------------------------
### preload Function
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/api/preload
The `preload` function serves as an optimization to load components or groups before they are actually rendered, improving initial load times.
```APIDOC
## preload
### Description
As an optimization, you can also decide to preload a component before it gets rendered.
### Method
N/A (This is a function call within the library, not an HTTP endpoint)
### Endpoint
N/A
### Parameters
#### `preload().component(componentName: string)`
- **componentName** (string) - Required - The name of the component to preload, as registered via the `register` function.
Returns: `Promise`
#### `preload().group(groupName: string)`
- **groupName** (string) - Required - The name of the group to preload, as specified in the `register` function.
Returns: `Promise`
### Request Example
```javascript
// Preload a specific component
preload().component('MyAwesomeComponent').then(() => {
console.log('Component preloaded successfully!');
});
// Preload a group of components
preload().group('AuthGroup').then(() => {
console.log('Group preloaded successfully!');
});
```
### Response
#### Success Response
- The Promises returned by `preload().component()` and `preload().group()` will resolve when the respective component or group has been successfully preloaded.
#### Response Example
(N/A - This function returns a Promise that resolves upon successful preload, rather than a JSON response body.)
```
--------------------------------
### Async Loading of One Specific Screen with react-native-bundle-splitter
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/guides/async-loading
Demonstrates how to preload a specific screen ('Dashboard') asynchronously before navigating to it. This ensures the component is loaded prior to usage, allowing for smooth transitions. The 'Dashboard' component must be wrapped with the `register` function from the library.
```typescript
import React from 'react';
import { Button, View, Text } from 'react-native';
import { preload } from 'react-native-bundle-splitter';
const REGISTERED = 'REGISTERED';
const doLoginRequest = (): Promise<{ status: string }> => new Promise((resolve) => {
setTimeout(() => resolve({ status: REGISTERED }), 3000);
})
class HomeScreen extends React.Component {
render() {
return (
Login
);
}
doLogin = async () => {
const [{ status }] = await Promise.all([
doLoginRequest(),
preload().component('Dashboard')
]);
if (status === REGISTERED) {
this.props.navigation.navigate('Dashboard');
}
}
}
```
```typescript
// dashboard/index.ts
import { register } from 'react-native-bundle-splitter';
export default register({ require: () => require('./View'), name: 'Dashboard' });
```
--------------------------------
### Async Loading of a Group of Screens with react-native-bundle-splitter
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/guides/async-loading
Illustrates how to preload a group of screens (e.g., 'Dashboard', 'Settings', 'Profile') tagged with a specific group name ('LOGGED') asynchronously. This is useful when multiple screens need to be ready after a certain condition, like user login. Screens intended for grouping must be registered with a `group` property.
```typescript
// home.ts
import { preload } from 'react-native-bundle-splitter';
// ... Assume doLoginRequest and REGISTERED are defined as in the single screen example
doLogin = async () => {
const [{ status }] = await Promise.all([
doLoginRequest(),
preload().group('LOGGED')
]);
if (status === REGISTERED) {
this.props.navigation.navigate('Dashboard');
}
}
// ...
```
```typescript
// dashboard/index.ts
import { register } from 'react-native-bundle-splitter';
export default register({ require: () => require('./View'), group: 'LOGGED' });
```
```typescript
// settings/index.ts
import { register } from 'react-native-bundle-splitter';
export default register({ require: () => require('./View'), group: 'LOGGED' });
```
```typescript
// profile/index.ts
import { register } from 'react-native-bundle-splitter';
export default register({ require: () => require('./View'), group: 'LOGGED' });
```
--------------------------------
### Register Component with Function-Based Static Options
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/guides/static-options
Illustrates how to pass a function to the `static` property of the `register` function to define dynamic or complex static options, like `navigationOptions`. This allows for more flexibility in configuring screen behavior based on navigation parameters.
```javascript
import { register } from 'react-native-bundle-splitter';
export default register({
require: () => require('./View'),
static: {
navigationOptions: ({ navigation }) => {
// all code from your component
return {
title: 'Home'
}
}
}
});
```
--------------------------------
### isCached
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/api/is-cached
Checks if a specified component or screen has already been preloaded by the bundle splitter.
```APIDOC
## isCached
### Description
Checks if a screen or component was already preloaded.
### Method
`isCached(componentName: string)`
### Endpoint
N/A (This is a function call within the library)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
* `componentName` (string) - Required - The name of the component or screen to check. This name should match the name used when registering the component with the `register` function.
### Request Example
```javascript
import { isCached } from 'react-native-bundle-splitter';
const componentName = 'MyScreen';
const cached = isCached(componentName);
if (cached) {
console.log(`${componentName} is already cached.`);
} else {
console.log(`${componentName} is not cached.`);
}
```
### Response
#### Success Response (boolean)
Returns `true` if the component is cached, `false` otherwise.
#### Response Example
```json
{
"cached": true
}
```
### Error Handling
This function does not explicitly define error responses. However, incorrect usage (e.g., passing a non-string `componentName`) might lead to runtime errors.
```
--------------------------------
### Basic Architecture: HomeScreen Component (TypeScript)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/guides/navigation
Defines a basic HomeScreen component using React Native. It includes a Text element and a Button to navigate to a 'Details' screen. The `goToDetails` method is a placeholder for navigation logic.
```typescript
import React from 'react';
import { Button, View, Text } from 'react-native';
class HomeScreen extends React.Component {
render() {
return (
Home Screen
);
}
private goToDetails = () => {
// call specific function to perform navigation
// in case of `react-navigation`: this.props.navigation.navigate('Details')
// see routes definition below for each library
}
}
```
--------------------------------
### Basic Architecture with TypeScript Screens
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/1.x/guides/navigation
Defines the basic structure for 'home.ts' and 'details.ts' screens in a React Native application. These screens use standard React Native components and include placeholder methods for navigation actions.
```typescript
import React from 'react';
import { Button, View, Text } from 'react-native';
class HomeScreen extends React.Component {
render() {
return (
Home Screen
);
}
private goToDetails = () => {
// call specific function to perform navigation
// in case of `react-navigation`: this.props.navigation.navigate('Details')
// see routes definition below for each library
}
}
```
```typescript
import React from 'react';
import { Button, View, Text } from 'react-native';
class DetailsScreen extends React.Component {
render() {
return (
Details Screen
);
}
private goToHome = () => {
// call specific function to perform navigation
// in case of `react-navigation`: this.props.navigation.navigate('Home')
// see routes definition below for each library
}
}
```
--------------------------------
### Add Bundle Analysis Script to package.json (JSON)
Source: https://kirillzyusko.github.io/react-native-bundle-splitter/docs/2.x/recipes/bundle-analysis
Adds a 'bundle:analysis' script to your package.json file. This script allows you to easily run the 'visualize-bundle' command to generate a bundle analysis report.
```json
{
"scripts": {
"bundle:analysis": "visualize-bundle"
}
}
```