Remap Lodash to Lodash-es in Webpack
This article explains how to configure Webpack aliases to cleanly
redirect standard Lodash imports directly to lodash-es. By
replacing the CommonJS distribution with its ECMAScript Modules (ESM)
counterpart, Webpack can perform effective dead-code elimination
(tree-shaking), reducing your application's bundle size without
requiring you to manually rewrite existing import statements across your
codebase.
Prerequisites
Ensure you have lodash-es installed in your project
alongside your standard dependencies:
npm install lodash-es
npm install --save-dev @types/lodash-es # optional, for TypeScript projectsThe Webpack Alias Configuration
In your webpack.config.js, define an alias within the
resolve property. Webpack aliases match module paths and
swap them out before bundling.
// webpack.config.js
const path = require('path');
module.exports = {
// ... other webpack settings
resolve: {
alias: {
// Remaps both top-level 'lodash' and path-based 'lodash/...' imports
lodash: 'lodash-es',
},
},
};How the Mapping Behaves
In Webpack, when an alias key does not include a trailing
$ symbol, it acts as a prefix matcher:
Named Imports:
import { debounce, cloneDeep } from 'lodash';Webpack resolves this to
lodash-es, importing only the exported functions. Webpack's tree-shaking mechanism analyzes the unused exports and strips them from the production bundle.Direct Subpath Imports:
import debounce from 'lodash/debounce';Webpack resolves this path prefix to
lodash-es/debounce, which imports the individual ES module directly.
Strict Top-Level Remapping
If your project exclusively uses named root imports and you want to
prevent subpath resolution edge cases, you can use the exact match
operator ($):
module.exports = {
resolve: {
alias: {
// Only matches import ... from 'lodash' exactly
'lodash$': 'lodash-es',
// Optionally map submodules explicitly if mixed conventions exist
'lodash': 'lodash-es',
},
},
};Using simply 'lodash': 'lodash-es' is generally
preferred because it covers both forms seamlessly.
Important Considerations
Babel Loader Exclusions: Most Webpack configurations exclude
node_modulesfrom transpilation via Babel or SWC. Becauselodash-esdistributes raw ES6 modules, legacy browser targets (like Internet Explorer 11) might require you to allowlodash-esthrough your transpiler:// webpack.config.js module: { rules: [ { test: /\.m?js$/, exclude: /node_modules\/(?!lodash-es)/, use: { loader: 'babel-loader', }, }, ], }CommonJS
require()Statements: Thelodash-eslibrary does not support CommonJSrequire()syntax. Ensure that dependencies or legacy local files do not rely onconst _ = require('lodash'), as this will produce an import execution error in an ESM environment.