Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my ES6 webpack bundle larger when using default imports instead of named imports?

I am using OpenLayers 6 and I import parts of the library using this notation:

import { Map, View } from 'ol';
import { Vector as VectorSource } from 'ol/source';
import { Vector as VectorLayer } from 'ol/layer';
// More in other files [...]

When running npm run dev I get a 9MB file for my project.

For testing purpose, I tried to replace these named imports by default imports:

import Map from 'ol/Map';
import View from 'ol/View';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';

Surprisingly, it reduced my bundled file to 6MB! It's 33% lighter, why is that? Shouldn't named imports be importing only required parts of modules?

EDIT 1

Following @Bergi comment, the library is available here. I use the last version which is installed through npm : v6.4.2

EDIT 2

As pointed out by @felixmosh answer, running npm run prod seems to reduce the size difference. I get a difference of 1KB from 886KB to 885KB.

like image 367
Marc Avatar asked Jul 31 '20 07:07

Marc


2 Answers

Tree shaking, is part of the minification process. In dev bundles this process is not applied.

Try to run in "production" mode, and compare the results.

like image 124
felixmosh Avatar answered Nov 03 '22 02:11

felixmosh


No, it shouldn't. It very depends on how internal libs are organized.

  • If it uses require inside, the lib will not be shaked
  • If it uses import * inside and uses this package, the whole * will be included
  • Even! if it uses import {name} from './names' it still might not be tree-shaked

There is a good starting article about how tree shaking works and how to help it: https://webpack.js.org/guides/tree-shaking/

like image 43
Drag13 Avatar answered Nov 03 '22 04:11

Drag13