Dynamic imports (powered by React Suspense) for components and hooks.
- 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',
})
- 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'
}
- Import from either provider in your components:
import React from 'react'
import { Header } from './mobile/Header'
const App = () => {
return (
<Header />
)
}
- Render
<Suspense>
providers around the dynamic elements:
import React, { Suspense } from 'react'
import { Header } from './mobile/Header'
const App = () => {
return (
<Suspense>
<Header />
</Suspense>
)
}
- All done! Now your app will dynamically load the modules it needs based on
the return value of your
useModuleProvider
hook.