Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 622
Eric Andrew Lewis Avatar asked Dec 20 '17 20:12

Eric Andrew Lewis


People also ask

Does webpack remove unused code?

To achieve this you can use the UglifyJS Plugin. With this setup, webpack will detect unused code and mark it as such however UglifyJS will actually cleanup that code and eliminate it from the bundle.

How does webpack detect dead code?

Using webpack for dead code detection Essentially, webpack is used to create a dependency graph of your application and combine every module of your project into a bundle. This makes the tool perfectly positioned to detect unused imports and exports, i.e., dead code.


2 Answers

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.

like image 133
Dancrumb Avatar answered Sep 28 '22 08:09

Dancrumb


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}]
}
like image 24
John Lee Avatar answered Sep 28 '22 10:09

John Lee