unused-webpack-plugin

raw JSON →
2.4.0 verified Sat Apr 25 auth: no javascript maintenance

A webpack plugin that detects and lists unused source files in one or more directories, helping developers identify dead code. Current stable version is 2.4.0, with maintenance through minor releases. It supports webpack 3 and 4 via the hooks API. Key differentiators: simple configuration (directories, exclude patterns, root), optional failure on unused files, and respect for .gitignore (default true). It does not remove files, only reports them, and is focused on development builds. Compared to alternatives like 'webpack-deadcode-plugin', it is more minimal and relies on directories rather than webpack's module graph exclusively.

error Error: Cannot find module 'webpack'
cause webpack is a peer dependency not installed automatically.
fix
Run 'npm install webpack' or ensure webpack is in your devDependencies.
error TypeError: UnusedWebpackPlugin is not a constructor
cause Incorrect import: using destructured import instead of default require.
fix
Use 'const UnusedWebpackPlugin = require('unused-webpack-plugin');' (no destructuring).
error No unused files found, but I know there are unused files.
cause Directories option may not include all relevant directories or exclude patterns are too broad.
fix
Check that 'directories' array includes every source folder and adjust 'exclude' patterns (e.g., remove 'node_modules/**' if already ignored).
breaking v2.0.0 switched to webpack 4 hooks interface, breaking compatibility with webpack <3.
fix Upgrade to webpack 4+ or use v1.2.0 for webpack 3 support.
deprecated Plugin is in maintenance mode; no new features are planned.
fix Consider alternatives like webpack-deadcode-plugin or unimported.
gotcha Plugin does not detect unused exports within files; it only lists files that are never imported.
fix Use tools like ESLint with no-unused-vars or webpack-deadcode-plugin for unused exports.
gotcha Directories must be absolute paths; relative paths may fail silently.
fix Always use path.join(__dirname, 'dir') or path.resolve() to define directories.
npm install unused-webpack-plugin
yarn add unused-webpack-plugin
pnpm add unused-webpack-plugin

Shows minimal webpack config with the UnusedWebpackPlugin, scanning 'src' directory, excluding test files, and setting root for relative output.

const path = require('path');
const UnusedWebpackPlugin = require('unused-webpack-plugin');

module.exports = {
  // webpack configuration
  plugins: [
    new UnusedWebpackPlugin({
      // Source directories to scan
      directories: [path.join(__dirname, 'src')],
      // Exclude patterns (e.g., test files)
      exclude: ['*.test.js', '*.spec.js', 'node_modules/**'],
      // Root directory for relative paths (optional)
      root: __dirname,
      // Fail build if unused files found (optional, default false)
      failOnUnused: false,
      // Respect .gitignore (default true)
      useGitIgnore: true,
    }),
  ],
};