Optimizing Lodash imports with jscodeshift
Since the beginning of the year, I’ve spent a lot of time at work getting ready for Google Core Web Vitals-ageddon. Most of the techniques we’ve tried are fairly well-documented and I don’t want to retread the great advice and tutorials that are already out there (although I should put together a roundup of links). A few have required a little more investigation and experimentation, though, and those seemed worth writing up.
Remove unused JavaScript! Avoid enormous network payloads!
One easy trick for creating huge JavaScript bundles and making Google angry is importing the entire Lodash library when you only use a few methods. A lot has been written on Lodash and bundle sizes and best practices for imports (I’m partial to The Correct Way to Import Lodash Libraries - A Benchmark on BlazeMeter) but what I found lacking were tips on how to update an older, monolithic Rails app with inconsistent import patterns and the continual risk of unmanageable merge conflicts.
Enter jscodeshift.
jscodeshift is a toolkit that allows you to run codemods over JavaScript files and it was a lifesaver in this situation. According to the article above, direct imports are the way to go and jscodeshift makes it possible to instantly transform any files:
- Importing the full library (
import _ from 'lodash'
) - Importing methods from Lodash with curly brackets (
import { name } from 'lodash'
) - Calling methods starting with
_.
To get started with jscodeshift, run
npm install -g jscodeshift
to install it globally and follow along below.
Continue Reading