Eric Andrew Lewis
Eric Andrew Lewis

Reputation: 1366

How to find unused files in a Webpack project?

I have a JavaScript project that is built with Webpack which I know has a lot of dead code files. How can I find source files that aren't used in the project?

Upvotes: 17

Views: 20833

Answers (3)

Gustavo Garcia
Gustavo Garcia

Reputation: 3243

Use Knip to get the job done. Lists unused files, types, modules and prop-types.

Just run:

npx knip

More details of how knip integrates with webpack: https://knip.dev/explanations/plugins#webpack

Upvotes: 2

John Lee
John Lee

Reputation: 1141

Tried using various webpack plugins, but ran into out of memory issues with each plugin. I think the easiest solution for a create-react-app bootstrapped application is to use ESLint.

Use the no-unused-modules which is now a part of eslint-plugin-import.

After setting up eslint, installing eslint-plugin-import, add the following to the rules:

"rules: {
  ...otherRules,
  "import/no-unused-modules": [1, {"unusedExports": true}]
}

Upvotes: 9

Dancrumb
Dancrumb

Reputation: 27549

There are a few plugins, but the UnusedFilesWebpackPlugin appears to be the most popular.

An example use is:

new UnusedFilesWebpackPlugin({
    failOnUnused: environment !== 'development',
    patterns: ['src/components/**/*.jsx', 'src/store/**/*.js', 'sass/**/*.scss'],
    ignore: ['**/LocalVideoDemo.jsx'],
  })

This will check for unused JSX files in the components directory, unused JS files in the Redux store directory and unused SCSS files. It will ignore whether or not the LocalVideoDemo.jsx file is included.

Upvotes: 13

Related Questions