vite-plugin-react-lazy
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

vite-plugin-react-lazy

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

Get Started

  1. Add the plugin to your Vite config:
import reactLazy from 'vite-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.

Package Sidebar

Install

npm i vite-plugin-react-lazy

Weekly Downloads

4

Version

0.1.1

License

MIT

Unpacked Size

11.2 kB

Total Files

7

Last publish

Collaborators

  • aleclarson