Babel plugin that automatically transforms Lodash imports to cherry-pick specific modules for bundle size optimization
npx @tessl/cli install tessl/npm-babel-plugin-lodash@3.3.0babel-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.
npm install --save-dev babel-plugin-lodashThe 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";{
"plugins": ["lodash"],
"presets": [["@babel/env", { "targets": { "node": 6 } }]]
}{
"plugins": [["lodash", { "id": ["lodash", "lodash-es"], "cwd": "/custom/path" }]],
"presets": [["@babel/env", { "targets": { "node": 6 } }]]
}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);The plugin operates during Babel's AST transformation phase and consists of several key components:
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 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" }]]
}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 };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."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);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 } }]]
}
}
}]
}
};By default, the plugin supports these Lodash distributions:
The plugin can be configured to work with other similar libraries by specifying them in the id option.
.chain()) are not supported