36
loading...
This website collects cookies to deliver better user experience
--splitting
, so you may want to check out the documentation before you will start building something very complex with it.index.html
:<!-- index.html -->
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Lazy load in esbuild</title>
<link rel="shortcut icon" href="#" />
<div id="view"></div>
<script type="module" src="./dist/index.js"></script>
</head>
<body></body>
</html>
dist
folder.src/index.js
:const view = document.getElementById("view");
view.innerHTML = `<button id="pdf-button">Generate PDF</button>
<br>
<iframe id="pdf" style="width: 350px; height: 600px"></iframe>`;
import("pdf-lib").then(({ PDFDocument }) => {
const pdfButton = document.getElementById("pdf-button");
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;
});
});
pdf-lib
. You can read more about dynamic imports on mdn, but in short, they are a part of the es-module specification. In short - it's loading another file during the runtime, and resolving a promise when it's available.$ npm init -y
$ npm install --save esbuild pdf-lib
package.json
:{
...
"scripts": {
...
"build": "esbuild src/index.js --bundle --outdir=dist --splitting --format=esm"
}
...
src/index.js
- the entry point of the application--bundle
- we tell the esbuild to bundle the whole application--outdir=dist
- because of using splitting, just specifying the output file with --outfile
is not enough - esbuild needs directory to put all chunks it creates there--splitting
- we turn on the experimental splitting behavior--format=esm
- another requirement of splitting to work - as of now, it's only working with es-modules output