Best way to import lodash
Here is how I import lodash in my projects :
import _findIndex from 'lodash/findIndex.js'
And here is why :
- It works because inside the installed lodash package there is an individual file for each lodash methods.
- You should not :
import _ from 'lodash'
because it will include ALL of lodash inside your bundled code. You should instead pick only the methods you need. (search for "tree shaking" for more details) - You could also import specific methods like that :
import { findIndex } from 'lodash'
, but it makes it harder to find references to lodash methods later because some are named like other native javascript methods (ex: filter, find, min, max, etc.) - You could also omit the extension like that :
import _findIndex from 'lodash/findIndex'
in environments such as webpack because webpack will handle the lack of file extension. But in a nodejs environment it won't work. (You will face this error :Error [ERR_MODULE_NOT_FOUND]: Cannot find module.
)