babel-plugin-danger-remove-unused-import

raw JSON →
2.0.0 verified Sat Apr 25 auth: no javascript deprecated

Babel plugin to remove unused imports, reducing bundle size. Version 2.0.0 as of latest release. Updated sporadically; last commit 2020. Key differentiator: aggressively removes imports even if side effects exist (hence 'dangerous'), with opt-out via ignore option. Alternatives (babel-plugin-transform-remove-imports) are less aggressive. Only supports ESM imports, not CommonJS require statements.

error Plugin threw: Cannot find module 'babel-plugin-danger-remove-unused-import'
cause Package not installed or placed in wrong plugins array path.
fix
Run npm install babel-plugin-danger-remove-unused-import --save-dev and ensure correct babel.config.js plugins entry.
error TypeError: Cannot read property 'references' of undefined
cause Plugin not compatible with Babel 7.x parser or used without proper preset/env.
fix
Use @babel/preset-env and ensure Babel version 6 or 7 compatibility in plugin's peerDependencies.
error The plugin does not remove imports that are used as type annotations
cause Plugin only checks runtime references, not TypeScript type usage.
fix
Use TypeScript compiler or type-aware plugin for type-only imports.
breaking Plugin removes imports that may have side effects (e.g., import 'polyfill'). Use ignore option to preserve.
fix Add known side-effect imports to ignore array: { ignore: ['polyfill', 'style.css'] }
deprecated Package not updated since 2020; no support for Babel 7.x modern features.
fix Consider alternatives like babel-plugin-transform-remove-imports or custom logic.
gotcha Does not handle dynamic imports or require() statements; only static ESM imports.
fix Use plugin only for static import removal; dynamic imports remain.
npm install babel-plugin-danger-remove-unused-import
yarn add babel-plugin-danger-remove-unused-import
pnpm add babel-plugin-danger-remove-unused-import

Show basic usage: configure plugin with ignore option to preserve React imports while removing unused lodash import.

// babel.config.js
module.exports = {
  plugins: [
    ['danger-remove-unused-import', { ignore: ['react'] }]
  ]
};

// Input: import unused from 'unused-module';
// Output: (import removed)

const plugin = require('babel-plugin-danger-remove-unused-import');
const babel = require('@babel/core');
const code = `import _ from 'lodash'; import React from 'react'; console.log('hi');`;
babel.transformSync(code, { plugins: [[plugin, { ignore: ['react'] }]] });
// Result: import React from 'react'; console.log('hi');