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();
}