Search code examples
expocode-splittingreact-native-web

How to code split with Expo web (React Native Web)?


Is there a recommended approach for code splitting in Expo web projects?

I cant find anything in the docs, even on the web performance page: https://docs.expo.io/guides/web-performance/

Im surprised as this something a lot (possibly most) web apps are going to want to do. If it's not officially supported is there a workaround?


Solution

  • I think code splitting is supported out the box. Here is my text component:

    import React from 'react';
    import { StyleSheet, Text, View } from 'react-native';
    import Component from './component'
    
    export default function App() {
      return (
        <View style={styles.container}>
          <Text>Open up App.js to start working on your app!</Text>
          <Component />
        </View>
      );
    }
    

    Which produces this bundle in static/js/

    2.1a79eeb8.chunk.js       198 KB
    app.95f72b23.chunk.js     936 bytes
    runtime~app.34c76111.js   2 KB
    

    If I change my component import from this:

    import Component from './component'
    

    To use React.lazy:

    const Component = React.lazy(() => import('./component'));
    

    Then the resulting bundle is this:

    2.025243cb.chunk.js       198 KB
    3.6601a067.chunk.js       326 bytes
    app.70989548.chunk.js     859 bytes
    runtime~app.4aba9b3a.js   2 KB
    

    For a more opinionated solution you could use NextJS with Expo: https://docs.expo.io/guides/using-nextjs/