Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to config lodash tree shaking in vite

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

like image 892
Heaven Avatar asked Nov 14 '22 22:11

Heaven


1 Answers

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.

like image 150
Davor Badrov Avatar answered Dec 31 '22 04:12

Davor Badrov