Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack import * messes tree shaking?

I read this here - https://www.thedevelobear.com/post/5-things-to-improve-performance/ - that doing importing all things from a library will not allow tree shaking to remove it, even if it is not used. I don't believe this, is it really true? I would think that tree shaking would identify that none of the functions except a couple were used, and then remove those.

There is a really easy way to reduce bundle size by just checking your imports. When performing methods or components from 3rd party libraries, make sure you import only the things you need, not the whole library itself. For instance, if you’re using lodash and need the fill method, import it directly instead of calling it on lodash object:

// Instead of this

import _ from ‘lodash’

let array = [1, 2, 3];
_.fill(array, '🐻');

// Do this

import { fill } from ‘lodash’

let array = [1, 2, 3];
fill(array, '🐻');
like image 982
Noitidart Avatar asked Nov 21 '18 15:11

Noitidart


1 Answers

Using current version of Webpack (5.3.0), this is not true. With the following files:

// src/index.js
import * as a from './modules'

console.log(a.foo)
// Or: console.log(a.baz.foo)
// src/modules.js
export const foo = 'foo'
export const bar = 'bar'
export const baz = {
  foo: 'foo',
  bar: 'bar',
}

Webpack outputs:

// dist/main.js
(()=>{"use strict";console.log("foo")})();

Based on this Github issue, it was not true even at the time of the previous answer.

like image 162
cdoublev Avatar answered Oct 03 '22 23:10

cdoublev