or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

babel-plugin-lodash

babel-plugin-lodash is a Babel plugin that automatically transforms Lodash imports to cherry-pick specific modules, enabling significant bundle size reduction by importing only the Lodash functions that are actually used in the code. The plugin provides seamless optimization for applications using Lodash by converting generic imports into specific module imports without requiring developers to manually manage individual function imports.

Package Information

  • Package Name: babel-plugin-lodash
  • Package Type: npm
  • Language: JavaScript (ES6+)
  • Installation: npm install --save-dev babel-plugin-lodash

Core Imports

The plugin is imported and configured through Babel configuration files rather than direct code imports:

{
  "plugins": ["lodash"]
}

For programmatic usage:

const babelPluginLodash = require("babel-plugin-lodash");

Or with ES modules:

import babelPluginLodash from "babel-plugin-lodash";

Basic Usage

Babel Configuration (.babelrc)

{
  "plugins": ["lodash"],
  "presets": [["@babel/env", { "targets": { "node": 6 } }]]
}

With Options

{
  "plugins": [["lodash", { "id": ["lodash", "lodash-es"], "cwd": "/custom/path" }]],
  "presets": [["@babel/env", { "targets": { "node": 6 } }]]
}

Transformation Examples

Input:

import _ from 'lodash';
import { add } from 'lodash/fp';

const addOne = add(1);
_.map([1, 2, 3], addOne);

Output (after transformation):

import _add from 'lodash/fp/add';
import _map from 'lodash/map';

const addOne = _add(1);
_map([1, 2, 3], addOne);

Architecture

The plugin operates during Babel's AST transformation phase and consists of several key components:

  • Main Plugin Function: The core Babel plugin that returns visitor object for AST transformation
  • Store System: Manages package paths and module caching for efficient lookups
  • Import Module System: Handles generation of specific module imports using Babel helpers
  • Configuration System: Processes plugin options and discovers available modules
  • Module Cache: Caches discovered module information for performance optimization

Capabilities

Plugin Function

The main plugin factory function that creates the Babel transformation visitor.

/**
 * Main Babel plugin factory function
 * @param {Object} babel - Babel instance with types
 * @param {Object} babel.types - Babel types for AST manipulation
 * @returns {Object} Plugin object with visitor
 */
function babelPluginLodash({ types }): { visitor: Object };

Plugin Configuration

Plugin accepts configuration options to customize transformation behavior.

interface PluginOptions {
  /** Package IDs to transform - defaults to ['lodash', 'lodash-es', 'lodash-compat'] */
  id?: string | string[];
  /** Current working directory for module resolution - defaults to process.cwd() */
  cwd?: string;
}

Configuration Examples:

// Single package
{
  "plugins": [["lodash", { "id": "lodash-es" }]]
}

// Multiple packages
{
  "plugins": [["lodash", { "id": ["lodash", "async", "ramda"] }]]
}

// Custom working directory
{
  "plugins": [["lodash", { "cwd": "/path/to/project" }]]
}

Transformation Patterns

The plugin handles various import and usage patterns:

// Named imports transformation
// Input: import { map, filter } from 'lodash';
// Output: import _map from 'lodash/map'; import _filter from 'lodash/filter';

// Default import with member access transformation  
// Input: import _ from 'lodash'; _.map(data, fn);
// Output: import _map from 'lodash/map'; _map(data, fn);

// Export re-transformation
// Input: export { map } from 'lodash';
// Output: import _map from 'lodash/map'; export { _map as map };

Error Handling

The plugin throws specific errors for unsupported patterns:

// Chain sequence error - thrown when .chain() is detected
// Error message: "Lodash chain sequences are not supported by babel-plugin-lodash.
// Consider substituting chain sequences with composition patterns.
// See https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba"

// Unknown module error - thrown when importing non-existent Lodash method
// Error message: "The 'packageId' method \`methodName\` is not a known module.
// Please report bugs to https://github.com/lodash/babel-plugin-lodash/issues."

Programmatic Usage

For direct programmatic usage with Babel:

/**
 * Transform code using babel-plugin-lodash programmatically
 */
const babel = require('@babel/core');
const babelPluginLodash = require('babel-plugin-lodash');

const result = babel.transform(sourceCode, {
  plugins: [babelPluginLodash]
});

Example:

const babel = require('@babel/core');
const babelPluginLodash = require('babel-plugin-lodash');

const sourceCode = `
import _ from 'lodash';
_.map([1, 2, 3], x => x * 2);
`;

const result = babel.transform(sourceCode, {
  plugins: [babelPluginLodash]
});

console.log(result.code);
// Output: import _map from "lodash/map"; _map([1, 2, 3], x => x * 2);

Webpack Integration

Integration with webpack through babel-loader:

// webpack.config.js
module.exports = {
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          plugins: ['lodash'],
          presets: [['@babel/env', { targets: { node: 6 } }]]
        }
      }
    }]
  }
};

Supported Packages

By default, the plugin supports these Lodash distributions:

  • lodash - Standard Lodash library
  • lodash-es - ES modules version of Lodash
  • lodash-compat - Compatibility version of Lodash

The plugin can be configured to work with other similar libraries by specifying them in the id option.

Limitations

  • ES2015 imports required: You must use ES2015 import statements to load Lodash
  • No chain sequences: Chain sequences (.chain()) are not supported
  • No modularized packages: Individual method packages from npm are not supported
  • Babel 6+ and Node.js 4+ required: Older versions are not supported

Performance Considerations

  • Module caching: The plugin caches module information for better performance across multiple files
  • Lazy evaluation: Import transformations are only applied when modules are actually used
  • Bundle size reduction: Significantly reduces bundle size by eliminating unused Lodash functions
  • Tree shaking compatibility: Works well with modern bundler tree shaking capabilities