Re.Pack: Module Federation for Large Scale React Native Apps

Scale your React Native development with Webpack 5/Rspack, dynamic module loading, and true microfrontend architecture

Large-scale React Native applications face unique challenges that small projects never encounter. As your codebase grows from thousands to hundreds of thousands of lines, traditional bundling approaches begin to crumble under the weight of complexity. Build times stretch into minutes or hours, bundle sizes balloon, and developers find themselves waiting for compiles instead of shipping features.

Re.Pack emerges as a modern solution to these scalability challenges, bringing web development's Module Federation pattern to the React Native ecosystem. This comprehensive guide covers everything you need to know about implementing Re.Pack in your projects, from basic setup to advanced optimization strategies.

For teams building complex mobile applications, adopting a modular architecture early can prevent technical debt from accumulating. Our mobile app development services help organizations design scalable architectures that accommodate growth while maintaining development velocity.

The Scaling Problem in React Native

When React Native projects grow beyond a certain threshold, several interconnected problems emerge that compound each other. The JavaScript bundle that once compiled in seconds now takes minutes to bundle, and the application that launched instantly now leaves users staring at splash screens. These aren't separate issues but symptoms of a fundamental architectural limitation in how traditional bundlers handle large codebases.

According to React Native bundle optimization research, bundle size directly impacts user experience and app store performance metrics.

Build Time Degradation

Traditional bundlers like Metro process your entire codebase as a single unit during each build. This approach works perfectly for small applications but becomes increasingly inefficient as your project grows. Every change, regardless of how small, requires reprocessing the entire bundle. A one-line fix to a utility function triggers a full rebuild, wasting developer time and breaking flow state. For teams practicing continuous integration, this translates directly to longer feedback loops and slower iteration cycles.

This is particularly impactful for enterprise React Native applications where multiple teams work on shared codebases and rapid iteration is essential for competitive advantage.

Bundle Size Inflation

The monolithic bundle approach means users download your entire application on first launch, regardless of which features they actually use. A banking app where most users only check their balance still ships the entire loan calculator, investment portfolio tracker, and support chat module. This impacts first-launch time, increases update download sizes, and consumes unnecessary storage on user devices. In markets with slower connections or limited data plans, this friction directly affects user acquisition and retention.

Our approach to mobile app performance optimization addresses these challenges through careful architecture planning and modern bundling strategies.

Code Organization Challenges

Large codebases require careful organization to remain maintainable, but traditional bundling offers limited support for true modular architecture. Teams resort to package managers, monorepo structures, and strict discipline to maintain boundaries between application domains. These workarounds add complexity without addressing the underlying architectural limitation--there's no mechanism to load code on demand or share dependencies between application modules at runtime.

Understanding Module Federation in React Native

Module Federation, introduced by Webpack, revolutionized how web applications handle code splitting and dependency sharing across multiple build artifacts. The core insight is that applications can expose and consume modules from other applications at runtime, enabling true microfrontend architectures. Re.Pack brings this capability to React Native, replacing Metro with a build system based on Webpack or Rspack that understands and implements Module Federation.

Core Concepts

Re.Pack introduces several key concepts that developers must understand to effectively leverage its capabilities. The host application serves as the primary container that coordinates module loading and manages the runtime environment. Remotes are separate build artifacts that expose modules for consumption by the host or other remotes. Exposes are the actual modules or components that a remote makes available to consumers. Together, these concepts enable a distributed architecture where code lives in logical modules that can be developed, built, and deployed independently.

Architecture Benefits

The architecture unlocked by Module Federation provides significant advantages over monolithic approaches. Development teams can work on different application features in parallel without stepping on each other's code. A team owning the checkout flow doesn't need to coordinate with the team working on product discovery. Each team builds their module as a remote, and the host application consumes these remotes without needing to know implementation details. This decoupling accelerates development velocity and reduces synchronization overhead.

Runtime Module Resolution

Unlike traditional code splitting that happens at build time, Module Federation performs module resolution at runtime. When a user navigates to a feature for the first time, the application requests the corresponding remote module from a configured URL. This enables true on-demand loading--users never download code they don't use. It also enables dynamic updates: you can deploy bug fixes or new features to remotes without requiring users to update the entire application. This capability proves especially valuable for A/B testing, phased rollouts, and hot-fixing production issues without app store review cycles.

Re.Pack Core Features and Capabilities

Re.Pack delivers its Module Federation capabilities through a carefully designed feature set that addresses the full spectrum of large-scale React Native development needs. Understanding these features helps architects make informed decisions about when and how to adopt Re.Pack in their projects.

As documented in the Callstack Re.Pack documentation, the system provides comprehensive support for modern mobile application architecture.

Drop-In Metro Replacement

One of Re.Pack's most practical features is its design as a drop-in replacement for Metro. This means teams can migrate existing React Native applications to Re.Pack without rewriting their codebase. The bundler understands React Native's module system, supports all standard React Native APIs, and integrates with the existing development workflow. Developers run repack start instead of react-native start, and the development server handles hot module replacement, source map generation, and all the features they've come to expect from Metro.

Webpack and Rspack Support

Re.Pack supports both Webpack 5 and Rspack as underlying bundlers, giving teams choice based on their specific needs. Webpack offers extensive plugin ecosystem and proven stability in production environments. Rspack, a high-performance bundler written in Rust, provides dramatically faster build times while maintaining compatibility with Webpack plugins and configuration patterns. Teams can benchmark both options against their specific codebase to determine which delivers better results for their use case.

Code Splitting and Dynamic Loading

Beyond traditional code splitting, Re.Pack enables fine-grained control over how and when code loads into the application. Developers can expose individual components, entire screens, or utility modules as federated remotes. The remote configuration specifies which modules to expose and where consumers should request them from. This granularity allows teams to optimize the loading strategy for each module based on user behavior--frequently used features load eagerly, while rarely-used administrative functions load only when accessed.

Implementing feature flags for React applications complements code splitting by allowing you to control feature exposure at runtime without deploying new code.

Tree Shaking Optimization

Re.Pack's underlying bundlers perform aggressive tree shaking to eliminate dead code from production builds. Unlike simple code splitting that separates bundles, tree shaking actually removes unused exports from included modules. If a utility library exports 50 functions but the application only uses 3, the bundled output contains only those 3 functions. This optimization significantly reduces bundle size without requiring developers to manually prune dependencies or create separate build configurations.

For teams focused on React Native performance optimization, implementing tree shaking is one of the most impactful initial improvements.

Implementing Re.Pack in Your Project

Migrating an existing React Native application to Re.Pack requires careful planning but follows a well-defined path. The process involves installation, configuration, remote creation, and gradual migration of application modules.

Installation and Initial Setup

Installation
1npm install @callstack/repack --save-dev

The minimal configuration establishes Re.Pack as the bundler and sets up basic Module Federation:

webpack.config.js
1const { withRePack } = require('@callstack/repack');2const path = require('path');3 4module.exports = withRePack({5 projectRoot: __dirname,6 entry: './index.js',7 platforms: ['ios', 'android'],8 modules: {9 resolveAlias: {10 '@components': path.resolve(__dirname, 'src/components'),11 },12 },13 server: {14 port: 8081,15 },16});

Configuring Module Federation

Module Federation configuration defines how your application exposes and consumes remote modules. The host application specifies where to find remotes and which modules to load. Each remote specifies what it exposes and where its build artifacts are served from. This configuration enables the runtime resolution that makes on-demand loading possible.

The Module Federation plugin configuration specifies the name, remotes, and shared dependencies for each application.

webpack.config.js - Host Configuration
1module.exports = withRePack({2 plugins: [3 new RePackPlugin.ModuleFederation({4 name: 'host',5 remotes: {6 checkout: `checkout@https://checkout.example.com/remote-entry.json`,7 profile: `profile@https://profile.example.com/remote-entry.json`,8 },9 shared: {10 react: { singleton: true },11 'react-native': { singleton: true },12 },13 }),14 ],15});

Creating and Consuming Remotes

Remote applications build into artifacts that the host consumes at runtime. Each remote exposes its public API through the Module Federation plugin configuration. The exposed modules can include React components, utility functions, or entire feature slices.

webpack.config.js - Remote Configuration
1module.exports = withRePack({2 plugins: [3 new RePackPlugin.ModuleFederation({4 name: 'checkout',5 exposes: {6 './CheckoutScreen': './src/screens/CheckoutScreen',7 './PaymentForm': './src/components/PaymentForm',8 './useCart': './src/hooks/useCart',9 },10 filename: 'remote-entry.json',11 shared: {12 react: { singleton: true, requiredVersion: '18.2.0' },13 'react-native': { singleton: true, requiredVersion: '0.73.0' },14 },15 }),16 ],17});

Gradual Migration Strategy

Full migration to Re.Pack and Module Federation typically proceeds incrementally. Begin by establishing Re.Pack as the bundler without enabling Module Federation. Once the application builds successfully with the new bundler, identify a candidate feature for remote extraction--ideally one that's relatively isolated with clear boundaries. Migrate that feature to a remote, update the host to consume it remotely, and validate the complete flow. Repeat this process feature by feature, building team expertise and confidence while spreading migration effort over time.

Our software architecture consulting services can help teams plan and execute complex migrations like this with minimal risk.

Bundle Optimization Strategies

Beyond Module Federation, Re.Pack enables powerful bundle optimization techniques that reduce download sizes, improve launch times, and enhance the overall user experience. These optimizations work independently of Module Federation but compound its benefits.

According to React Native bundle optimization best practices, combining multiple optimization strategies produces the best results.

Tree Shaking Implementation

Tree shaking relies on ES module syntax and clean export patterns to eliminate unreachable code. Ensure all imports use named exports rather than default exports where possible, as named exports provide better dead code detection. Avoid patterns that prevent tree shaking, such as importing entire modules and using only a subset of their exports, or dynamically importing modules at runtime without using the imported values.

Tree Shaking Best Practices
1// Good - enables tree shaking2import { formatCurrency, parseAmount } from './utils/currency';3 4// Bad - prevents tree shaking5import * as CurrencyUtils from './utils/currency';

Code Splitting Patterns

Effective code splitting balances between granular loading and reasonable chunk sizes. Splitting every component into its own remote creates excessive network overhead that degrades performance. Conversely, keeping all code in monolithic remotes loses the benefits of on-demand loading. Identify natural module boundaries based on user flows--feature areas that users typically access in single sessions work well as remote boundaries. Use analytics to understand feature usage patterns and prioritize splitting for less-frequently-used features.

For React Native apps requiring push notifications integration, implementing code splitting can help reduce initial download size while maintaining full feature availability.

Dependency Management

Large applications often accumulate unnecessary dependencies over time. Use tools like react-native-bundle-visualizer to understand what's included in your bundle and identify opportunities for reduction.

Evaluate whether full library imports are necessary. Many libraries export individual functions that can be imported directly, reducing bundle impact:

Selective Dependency Imports
1// Instead of: import _ from 'lodash';2import chunk from 'lodash/chunk';3import orderBy from 'lodash/orderBy';

Hermes Engine Configuration

Enable Hermes in your application to benefit from its precompiled bytecode and optimized JavaScript engine. Hermes compiles JavaScript into bytecode during the build process, eliminating JIT compilation overhead on first launch. This results in measurably faster application startup times, particularly noticeable on lower-end devices.

For teams implementing React Native performance strategies, Hermes should be considered a baseline requirement for production applications.

Performance Monitoring and Optimization

Achieving optimal performance requires ongoing measurement and optimization. Establish baseline metrics before implementing changes, measure impact of optimizations, and monitor production performance to identify regressions.

Build Performance Metrics

Key Metrics to Track

Initial Bundle Time

How long from starting the build to producing a usable bundle

Incremental Build Time

How long changes take to propagate through HMR

Bundle Size

Total size of JavaScript bundles shipped to users

Remote Load Time

How long remote modules take to load on first access

Implementing a health check API in Node.js can complement these metrics by providing runtime monitoring of your build infrastructure and remote availability.

Comprehensive monitoring across build, runtime, and user experience metrics provides the visibility needed to continuously improve application performance.

When to Use Re.Pack

Re.Pack provides significant value for specific project profiles. Understanding when Re.Pack delivers the strongest return on investment helps justify the migration effort and set appropriate expectations.

Ideal Candidates for Re.Pack

Large applications with extensive codebases--typically exceeding 100,000 lines of JavaScript--benefit most from Re.Pack's architecture. These projects experience meaningful build time reductions and bundle size improvements that justify migration effort. Applications serving multiple user segments with different feature needs benefit from on-demand loading, as users only download code relevant to their usage patterns. Teams practicing micro-frontend or domain-driven architecture find Re.Pack's Module Federation support enables cleaner separation of concerns and independent deployment pipelines.

For organizations building scalable enterprise mobile applications, Module Federation provides the architectural foundation for sustainable growth.

Considerations for Smaller Projects

Smaller applications may not need Re.Pack's capabilities. If build times remain acceptable (under two minutes for clean builds), bundle sizes stay reasonable (under 50MB for initial download), and development velocity meets team needs, the migration overhead may not justify the benefits. Re.Pack introduces additional complexity in build configuration, deployment pipelines, and runtime module resolution. Evaluate whether current pain points warrant addressing or if simpler optimizations would suffice.

Common Patterns and Anti-Patterns

Learning from organizations that have successfully implemented Re.Pack helps avoid common pitfalls while adopting proven patterns.

Proven Patterns

Successful Re.Pack implementations share characteristics worth emulating. Teams that begin with non-critical features build expertise before tackling high-risk migrations. Those that establish clear ownership boundaries between remotes--specifying which team owns each remote and its API contract--maintain architectural integrity as teams scale. Organizations that implement runtime health monitoring for remote loading can quickly identify and address failures, whether from network issues or remote deployment problems.

According to practical Re.Pack implementation guidance, starting small and scaling gradually leads to the most successful deployments.

Anti-Patterns to Avoid

Several patterns lead to difficulties in Re.Pack implementations. Creating circular dependencies between remotes--where remote A depends on remote B and remote B depends on remote A--causes loading deadlocks and runtime failures. Exposing too many modules from a single remote defeats the purpose of code splitting and creates loading waterfalls where users download large chunks of code they don't need. Failing to version remote APIs creates breaking changes that affect consumers unexpectedly, requiring coordinated updates that undermine independent deployment benefits.

Conclusion

Re.Pack represents a significant advancement in React Native development tooling, bringing web-scale architecture patterns to mobile application development. For large-scale projects struggling with build times, bundle sizes, and code organization challenges, Re.Pack offers a proven solution that scales with application complexity. The investment in migration pays dividends through faster development cycles, smaller download sizes, and architectural flexibility that enables team autonomy and independent deployment.

The path to Re.Pack adoption requires careful planning, incremental migration, and ongoing optimization, but the destination--a scalable, performant, maintainable mobile application architecture--justifies the journey for teams facing the challenges of large-scale React Native development.

If your organization is considering modernizing a large React Native codebase, our team of experts can help assess your current architecture and develop a migration strategy that minimizes risk while maximizing benefits. Contact us to learn more about our React Native development services and how we can help you scale your mobile applications effectively.

Ready to Scale Your React Native Application?

Our team of React Native experts can help you implement modular architectures that support sustainable growth.

Sources

  1. Callstack Re.Pack Documentation - Official Re.Pack documentation and Module Federation implementation
  2. Callstack Bundle Optimization Guide - JavaScript bundle optimization techniques
  3. Solution Squares React Native Bundle Optimization Guide - Comprehensive bundle optimization strategies
  4. LogRocket Using Re.Pack for Large-Scale React Native - Practical implementation insights