12

Now, I'm using Vite2.x build my project with 'rollup-plugin-visualizer', I found it build entire lodash package in

so, how to config the vite2.x to reduce the lodash package size enter image description here

Heaven
  • 133
  • 1
  • 5

1 Answers1

14

I found this issue because I had a similar problem, maybe this helps someone in the future having a similar issue.

The easiest fix for this is to use imports like the following:

import uniqueId from "lodash/uniqueId";

This ensures that you add a minimal footprint to your production bundle when using lodash functions.

Another approach is to use the lodash-es lib which is properly tree shakeable, then you can use:

import { uniqueId } from "lodash-es";

By using the lodash-es lib you can safely import functions and your project won't end up with the entire lodash source in your production build.

What's the difference?

Why can you safely import the uniqueId from lodash-es but not from lodash?

If you compare the uniqueId source code you'll notice that lodash-es uses ES modules while plain lodash uses CommonJS modules.

Since Vite works with EcmaScript modules I think only those are tree-shakeable (can't find anything in their documentation), CommonJS modules are harder to tree-shake in general and you usually need to do some workarounds to treeshake them.

A bit more info on tree-shaking.

Davor Badrov
  • 543
  • 5
  • 12
  • Yet another way is to use the specific function modules, e.g. `lodash.chunk` if you want to use the `chunk` method. I did a comparison between this method and the other two mentioned, and the function module shaves off another kilobyte from the build. But to be honest i don't think that would make much of a difference, so either one of these three methods are fine. I suppose the `lodash-es` method might be the nicest because it's a simple drop-in replacement in your code. – Husky Feb 21 '22 at 12:36
  • 2
    A nicer way to use lodash-es is that, if you want to directly use _ to call lodash functions, you can import lodash-es like so: `import * as _ from 'lodash-es';` When you do this, Vite will automatically tree-shake the unused functions, meaning that it will have the same bundle size as `import {} from 'lodash-es';` without explicitly adding the used functions – khoi nguyen Apr 18 '23 at 03:29
  • 1
    @khoinguyen Thanks for this tip, saved a lot of migration work (and things like `_.get()` are easier to recognise than `get()`) – Ethan May 01 '23 at 06:15