How to Custom Build Lodash Using lodash-cli
Custom building the Lodash library allows developers to significantly
reduce JavaScript bundle sizes by including only the specific utility
functions required for a project. This article explains how to install
the lodash-cli utility, generate tailored Lodash builds
using various CLI arguments such as include and
category, specify export formats, and integrate the
compilation step into your build workflow.
1. Prerequisites and Installation
To use lodash-cli, you need Node.js and npm installed on
your machine. You can install the tool globally:
npm install -g lodash-cliAlternatively, you can run it directly without a permanent global
installation using npx:
npx lodash-cli <arguments>2. Basic Custom Builds
By default, running lodash generates the full library.
To generate a build containing only specific functions, use the
include flag followed by a comma-separated list of function
names (without spaces).
lodash include="map,filter,debounce,throttle"This command creates a lodash.custom.min.js file in your
current working directory, including only the specified functions and
their internal dependencies.
3. Using Categories
Lodash categorizes its methods into functional groups such as
collection, array, object, and
string. You can include entire categories using the
category flag:
lodash category="collection,object"You can also combine categories with specific functions:
lodash category="array" include="debounce,throttle"4. Excluding Methods
If you need most of a category or build but want to omit certain
heavy or unused methods, use the minus flag:
lodash category="collection" minus="shuffle,sample"5. Specifying Output Formats and Targets
You can configure output formats, environments, and file destinations using additional flags:
- Export Formats: Use the
exportsflag to define module definitions (es,amd,commonjs,node, orglobal).lodash include="cloneDeep,isEmpty" exports="es" - Output Path: Use the
-oor--outputflag to save the file to a specific path and name.lodash include="get,set" -o "./src/vendor/lodash.custom.js" - Development Build: By default, Lodash builds are
minified. Add the
developmentmodifier to output an unminified, readable version.lodash development include="chunk,compact"
6. Automating via package.json
To ensure consistency across development environments, add your
custom build command to your project's package.json
scripts:
{
"scripts": {
"build:lodash": "lodash include=\"debounce,throttle,get,set\" exports=\"es\" -o \"./src/utils/lodash.custom.js\""
},
"devDependencies": {
"lodash-cli": "^4.17.5"
}
}Running npm run build:lodash will regenerate the custom
bundle whenever your dependencies or utility requirements change.