babel-plugin-remove-unused-vars

raw JSON →
2.2.0 verified Sat Apr 25 auth: no javascript

A Babel plugin that automatically removes unused variables, imports, function arguments, and destructured bindings from JavaScript code, acting as a Babel-based autofix for ESLint's no-unused-vars rule. As of version 2.2.0, it supports source-to-source transformations and is intended for use as a build tool to clean up code. The plugin runs via Babel CLI or programmatically and handles common cases but has known limitations with deep assignment expressions. It is released under the MIT license with moderate maintenance cadence on GitHub, positioned as a more aggressive alternative to manual lint fixes or tree-shaking.

error Error: Cannot find module 'babel-plugin-remove-unused-vars'
cause Plugin not installed or not in node_modules.
fix
Run 'npm install --save-dev babel-plugin-remove-unused-vars' and ensure working directory has node_modules.
error TypeError: babel.transformSync is not a function
cause Using a string plugin name instead of the plugin function reference when calling Babel programmatically.
fix
Use: babel.transformSync(code, { plugins: [require('babel-plugin-remove-unused-vars')] })
error Unexpected token (1:0) when running Babel with --no-babelrc
cause Missing @babel/preset-env or other presets; --no-babelrc disables .babelrc but the plugin alone doesn't parse modern syntax.
fix
Add presets explicitly: npx babel --no-babelrc --presets @babel/preset-env --plugins babel-plugin-remove-unused-vars
gotcha Plugin may produce false positives (removing actually used variables) or false negatives (keeping unused variables). Always review git diff after transformation.
fix Run locally, inspect output with 'git diff', revert false removals manually.
gotcha Deep assignment expressions (e.g., const a = foo(b = something())) are not fully handled. The right side may be removed even if the left side is used.
fix Avoid deep assignments, or manually adjust after transformation.
gotcha Plugin is intended for source-to-source transformation, not for minification or bundling. It should be run early in the build pipeline.
fix Run before other transformations like minification.
npm install babel-plugin-remove-unused-vars
yarn add babel-plugin-remove-unused-vars
pnpm add babel-plugin-remove-unused-vars

Shows installation, configuration, CLI usage, and a simple transformation that removes unused imports and variables.

// Install: npm install --save-dev babel-plugin-remove-unused-vars
// .babelrc
{
  "plugins": ["babel-plugin-remove-unused-vars"]
}

// Or via CLI:
// npx babel --no-babelrc --retain-lines --plugins babel-plugin-remove-unused-vars --out-dir dist/ src/

// Input: src/index.js
import { unused } from './utils';
const a = 1;
const b = a;
console.log(b);

// Output: dist/index.js
import {} from './utils';
const b = 1;
console.log(b);