Optimize Core Web Vitals - FCP and LCP: Optimize bundle size by lazy loading heavy 3rd-party package

Resources https://nextjs.org/docs/pages/building-your-application/optimizing Bundle Analyzer Optimizing Package Bundling https://nextjs.org/docs/app/building-your-application/optimizing/package-bundling Setup and get reports Findings Static import of libraries with large package size For example, import { HeavyLibComponent } from 'heavy-lib'; import { runSomething } from 'heavy-lib'; Steps-by-steps Dynamically import components using Next.js next/dynamic https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#nextdynamic Change from import HeavyLibComponent from 'heavy-lib'; To import dynamic from 'next/dynamic'; const HeavyLibComponent = dynamic(() => import('heavy-lib')); Use import() to dynamically import modules/libraries to use functions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import Because the function runSomething needs to be called only when the event handler function handleClick is executed when the user clicks the button. Before the change, statically importing functions from a library at the top level of a module would cause any other JS importing this module to import the library code unused. Therefore, use import() instead to dynamically import functions from the library within the event handler function. Change from import { runSomething } from 'heavy-lib'; const handleClick = () => { runSomething(); } To const handleClick = async () => { const { runSomething } = await import('heavy-lib'); runSomething(); }

Mar 27, 2025 - 08:33
 0
Optimize Core Web Vitals - FCP and LCP: Optimize bundle size by lazy loading heavy 3rd-party package

Resources

Bundle Analyzer

Optimizing Package Bundling

Setup and get reports

Findings

Static import of libraries with large package size

For example,

import { HeavyLibComponent } from 'heavy-lib';
import { runSomething } from 'heavy-lib';

Steps-by-steps

Dynamically import components using Next.js next/dynamic

Change from

import HeavyLibComponent from 'heavy-lib';

To

import dynamic from 'next/dynamic';

const HeavyLibComponent = dynamic(() => import('heavy-lib'));

Use import() to dynamically import modules/libraries to use functions

Because the function runSomething needs to be called only when the event handler function handleClick is executed when the user clicks the button.

Before the change, statically importing functions from a library at the top level of a module would cause any other JS importing this module to import the library code unused.

Therefore, use import() instead to dynamically import functions from the library within the event handler function.

Change from

import { runSomething } from 'heavy-lib';

const handleClick = () => {
    runSomething();
}

To

const handleClick = async () => {
    const { runSomething } = await import('heavy-lib');
    runSomething();
}