Published on
·
Time to read
2 minute read

Perf Protip: Painless a-la-carte lodash

Blog post image
Authors

If you're like me, you run npm install --save lodash on every new project as a reflex. This habit means I always have access to that _.get(obj, 'super.deeply.nested.property.yo') goodness whenever I need it, but it also means every front-end bundle I build throws in all of lodash (~71KB) just for a couple of juicy functions I happen to be using.

Enter lodash v4 and its oh-so-helpful aliases. jdalton has done some magic here and sliced up his superfile into easy, digestable slices for each function for a-la-carte consumption without changing your dependencies or build configuration at all! Each function in lodash is available as its own file under its name within the node_modules/lodash directory, so if you're using browserify/webpack/rollup you can grab some easy-peasy byte savings with barely any effort.

For example, in my sample code below I replace const _ = require('lodash') with const get = require('lodash/get') and BOOM instant savings!

Before

const _ = require('lodash')

const myObj = {}
const color = _.get(myObj, 'favorite.color', 'red')
console.log(color)

After

const get = require('lodash/get')

const myObj = {}
const color = get(myObj, 'favorite.color', 'red')
console.log(color)

Making this simple change in my projects resulted in at least 50 KB savings for a few minutes of work, and I'm still able to bring in any function from the lodash the second I need it in the future.

NOTE: For the adventurous out there, jdalton also publishes each function as an entirely separate module, so you can npm install --save lodash.get and require('lodash.get') for even more savings as certain modules won't pull in shared functionality at all under this method, but I've found having the power of full lodash at my fingertips too comforting to leave just yet.