Reduce Lodash Size In Webpack

Jan 7, 2018

Lodash package size is 70KB (24KB if GZipped).

The following code will import entire lodash library, even though you just use the clone function.

import _ from lodashconst object = { 'name': 'Desmond' }const shallow = _.clone(object)

Using the following code will import clone only and significantly reduce the lodash bundle size. If you still want to maintain _ in your code, assigned imported function to _ object.

import clone from 'lodash/clone'const _ = { clone }const object = { 'name': 'Desmond' }const shallow = _.clone(object)

You can also customize and create your own global lodash _ object.

import keyBy from 'lodash/keyBy'import clone from 'lodash/clone'import map from 'lodash/map'global._ = { keyBy, clone, map }const shallow = _.clone(object)

If ESLint complaint of '_' is not defined, edit .eslintrc.js to add globals._ = true.

module.exports = {  ...  globals: {    '_': true  },...}

Sadly the following syntax doesn't work to reduce lodash bundle size (no tree shake).

import { clone } from 'lodash'

You can explore lodash-es which should support the following syntax to reduce bundle size.

import { clone } from 'lodash-es'

You can also look into babel-plugin-lodash (Modular Lodash builds without the hassle).

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.