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 projects

The 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:

  1. 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.

  2. 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