Lodash Support for RequireJS and Module Loaders
This article explains how the Lodash utility library integrates seamlessly with client-side module loaders like RequireJS. It details Lodash's built-in support for Asynchronous Module Definition (AMD), how to configure and load the library in a RequireJS environment, and strategies for loading individual utility functions to optimize application bundle sizes.
Built-In AMD Support via UMD
Lodash is distributed using a Universal Module Definition (UMD)
pattern. This allows the core library to automatically detect the
environment in which it is running. When loaded in a browser where an
AMD loader is active, Lodash checks for the existence of
define as a function and define.amd as an
object:
if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
define(function() {
return _;
});
}Because Lodash registers itself anonymously, module loaders can name and map it flexibly within application configurations without encountering naming collisions.
Configuring Lodash in RequireJS
To use Lodash with RequireJS, map the path to the Lodash file inside
your requirejs.config definition. This makes Lodash
available as a dependency across your project under a consistent
alias.
requirejs.config({
paths: {
'lodash': 'vendor/lodash.min'
}
});Once configured, inject Lodash into any module using its mapped identifier:
define(['lodash'], function(_) {
var numbers = [1, 2, 3, 4, 5];
var doubled = _.map(numbers, function(n) {
return n * 2;
});
return doubled;
});Modular Loading and
the lodash-amd Package
Loading the full Lodash build can introduce unnecessary weight if an application only requires a handful of utility functions. Lodash addresses this through modular builds.
1. lodash-amd
Lodash previously published a dedicated lodash-amd
distribution where every function is structured as an individual AMD
module. This allows developers to load only specific functions directly
through RequireJS:
define(['lodash/map', 'lodash/filter'], function(map, filter) {
var data = [1, 2, 3, 4];
var evens = filter(data, function(n) { return n % 2 === 0; });
return map(evens, function(n) { return n * 10; });
});2. Path Mapping for Granular Imports
Using modern npm-installed Lodash builds with RequireJS, you can map the library directory in your configuration to enable modular imports:
requirejs.config({
packages: [
{
name: 'lodash',
location: 'node_modules/lodash',
main: 'lodash.js'
}
]
});Dropping in Lodash for Underscore
RequireJS allows mapping aliases to replace older dependencies. Since
Lodash provides full API compatibility with Underscore.js, you can map
legacy underscore requests directly to Lodash:
requirejs.config({
map: {
'*': {
'underscore': 'lodash'
}
},
paths: {
'lodash': 'vendor/lodash.min'
}
});Any AMD module requesting underscore receives the Lodash
instance instead, requiring no changes to existing codebases.