简体   繁体   中英

ES6 dynamic imports is supposed to increase my final bundle size?

I'm trying to await import for PDF.js , a very large library. So, in my main entry point I'm doing the following:

{
  (async () => {
    const pdfjsWorker = await import('pdfjs-dist/build/pdf.worker.entry');
    const pdfjsLib = await import('pdfjs-dist/build/pdf');
    pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;
      
    // Code using pdfjsLib here...
  })();
}

I expected my final bundle size a bit (maybe) larger than before. But now there are new chuncks 3.aa11bcbe.js , 4.d45ca641.js and 5.6292c84a.js (sum up to 600KB). What I'm doing wrong?

Chucks before :

在此处输入图片说明

And after :

在此处输入图片说明

But now there are new chuncks

That's what's supposed to happen.

If you did a normal import ( import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry' ), then the data is needed right away, and so webpack would put all the code into an existing chunk (probably chunk 0). Chunk 0 would be about 600k larger, and the pdf code would thus be downloaded as soon as the page is loaded along with everything else.

Since you did a dynamic import, the data does not need to be loaded as soon as the app boots, so it can be left out from chunk 0. Instead, it's put into separate chunks, and will only be loaded once these lines of code are reached.

Either way, the total size of your project is going to increase. The benefit of dynamic imports is that you can skip loading some of the code until it's actually needed. Or if it's never needed, then it doesn't need to be downloaded at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM