If you’re using webpack to bundle your application, then you can use webpack magic comments to have webpack instruct the browser to prefetch dynamic imports.
Next.js supports ES2020 dynamic import() for JavaScript. With it, you can import JavaScript modules dynamically and work with them. They also work with SSR.
Dynamically import the Hello component with loading component:
With no server-side rendering:
Lazy Loading components with React-Loadable
React-Loadable - a higher-order component for dynamically loading a module before rendering it, a loading component is rendered while the module is unavailable.
Use only what you need
For example,
change to:
OR in this case, you can use the Babel plugin for lodash.
// remove this import
import { javascript } from "@codemirror/lang-javascript"
// add this where needed access to {javascript}
const javascript = (await import("@codemirror/lang-javascript")).javascript;
import dynamic from 'next/dynamic'
const DynamicComponentWithCustomLoading = dynamic(
() => import('../components/hello'),
{ loading: () => <p>...</p> }
)
function Home() {
return (
<div>
<Header />
<DynamicComponentWithCustomLoading />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home
import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(
() => import('../components/hello3'),
{ ssr: false }
)
function Home() {
return (
<div>
<Header />
<DynamicComponentWithNoSSR />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home