DEV Community

Jen C.
Jen C.

Posted on • Edited on

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';
Enter fullscreen mode Exit fullscreen mode

Steps-by-steps

Dynamically import components using Next.js next/dynamic

Change from

import HeavyLibComponent from 'heavy-lib';
Enter fullscreen mode Exit fullscreen mode

To

import dynamic from 'next/dynamic';

const HeavyLibComponent = dynamic(() => import('heavy-lib'));
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

To

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

Top comments (0)