Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/aleclarson/vite-plugin-react-lazy
Seamless conditional imports with React Suspense
https://github.com/aleclarson/vite-plugin-react-lazy
Last synced: 19 days ago
JSON representation
Seamless conditional imports with React Suspense
- Host: GitHub
- URL: https://github.com/aleclarson/vite-plugin-react-lazy
- Owner: aleclarson
- License: mit
- Created: 2020-09-30T19:12:52.000Z (about 4 years ago)
- Default Branch: master
- Last Pushed: 2021-01-28T01:14:15.000Z (almost 4 years ago)
- Last Synced: 2024-10-12T06:31:51.137Z (25 days ago)
- Language: TypeScript
- Homepage:
- Size: 41 KB
- Stars: 4
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# vite-plugin-react-lazy
Dynamic imports (powered by React Suspense) for components and hooks.
## Get Started
1. Add the plugin to your Vite config:
```ts
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',
})
```2. Create the resolver module:
```ts
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'
}
```3. Import from either provider in your components:
```ts
import React from 'react'
import { Header } from './mobile/Header'const App = () => {
return (
)
}
```4. Render `` providers around the dynamic elements:
```ts
import React, { Suspense } from 'react'
import { Header } from './mobile/Header'const App = () => {
return (
)
}
```5. All done! Now your app will dynamically load the modules it needs based on
the return value of your `useModuleProvider` hook.