DEV Community

Marcin Wosinek
Marcin Wosinek

Posted on • Edited on

webpack 5 - lazy load library in application

Have you ever seen your app load very slow, just because you added a big, 3rd party library? A neat solution for that kind of case, it's to use lazy load - delaying a download of big chunks of code. This approach allows having some part of the application already working, while the rest is being loaded.

non lazy-load

example of application loading a big, pdf before starting the application:

import { PDFDocument } from "pdf-lib"; // synchronous import

// ...

pdfButton.addEventListener("click", async () => { 
  const pdfDoc = await PDFDocument.create();
  const page = pdfDoc.addPage([350, 400]);
  page.moveTo(110, 200);
  page.drawText("Hello World!");
  const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
  document.getElementById("pdf").src = pdfDataUri;
});
Enter fullscreen mode Exit fullscreen mode

lazy load in webpack

import(/* webpackChunkName: "pdf-lib" */ "pdf-lib").then(({ PDFDocument }) => {
  // ..

  pdfButton.addEventListener("click", async () => {
    const pdfDoc = await PDFDocument.create();
    const page = pdfDoc.addPage([350, 400]);
    page.moveTo(110, 200);
    page.drawText("Hello World!");
    const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
    document.getElementById("pdf").src = pdfDataUri;
  });
});
Enter fullscreen mode Exit fullscreen mode

import() is a dynamic import from javascript. Webpack translates "pdf-lib" to a new asset it creates dynamically. /* webpackChunkName: "pdf-lib" */ allow us to name the new asset. When I was removing this line, my lazy-loaded chunk was called 55.js - not the best name if ever somebody would have to troubleshoot some issues around it.

Interested in more?

Top comments (0)