Skip to content
This repository has been archived by the owner on Jan 4, 2021. It is now read-only.

Seamless conditional imports with React Suspense

License

Notifications You must be signed in to change notification settings

alloc/rollup-plugin-react-lazy

Repository files navigation

rollup-plugin-react-lazy

Dynamic imports (powered by React Suspense) for components and hooks.

Get Started

  1. Add the plugin to your Rollup config:
import reactLazy from 'rollup-plugin-react-lazy'

// In the "plugins" array
reactLazy({
  // Define which directories have identical filenames and exports.
  providers: {
    mobile: 'src/mobile',
    desktop: 'src/desktop',
  },
  // Define which module exports a `useModuleProvider` hook.
  resolver: 'src/useModuleProvider.js',
})
  1. Create the resolver module:
import { useMediaQuery } from 'react-responsive'

// React hook that returns the directory name to be imported from.
export const useModuleProvider = () => {
  return useMediaQuery({ maxWidth: 990 }) ? 'mobile' : 'desktop'
}
  1. Import from either provider in your components:
import React from 'react'
import { Header } from './mobile/Header'

const App = () => {
  return (
    <Header />
  )
}
  1. Render <Suspense> providers around the dynamic elements:
import React, { Suspense } from 'react'
import { Header } from './mobile/Header'

const App = () => {
  return (
    <Suspense>
      <Header />
    </Suspense>
  )
}
  1. All done! Now your app will dynamically load the modules it needs based on the return value of your useModuleProvider hook.

About

Seamless conditional imports with React Suspense

Resources

License

Stars

Watchers

Forks

Packages

No packages published