简体   繁体   中英

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 .

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.

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/

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