How to find unused files in a Webpack project?
Solution 1
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.
Solution 2
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}]
}
Related videos on Youtube
Comments
-
Eric Andrew Lewis almost 2 years
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?
-
luislhl almost 5 yearsThis only checks for unused imports in a file, not for files that are not imported anywhere.
-
John Lee almost 5 years@luislhl did you read the description on the module? It does 2 things, and I quote: "Reports: (1) modules without any exports (2) individual exports not being statically imported or required from other modules in the same project." Your comment of "Files that are not imported anywhere" will fall under second category. Admittedly, the plugin is not perfect, but it's attempting to do exactly what you stated.
-
luislhl almost 5 yearsYou are right @John Lee, sorry. I wasn't the one who downvoted you, though.
-
John Lee almost 5 yearsNo problem @luislhl. 8-)
-
Denis Howe over 3 yearsI love eslint but gave up trying to configure this to do all the same module resolution as webpack (aliases, file name extensions, etc.). Doesn't a webpack plugin make more sense if you're using both?
-
John Lee over 3 years@DenisHowe as mentioned in my answer, Webpack was also my initial attempt as it seemed like the logical solution. However, I ran into memory issues. Perhaps due to different project sizes, it works well for you. I haven't tried this in over a year, so I should try to revisit the webpack solution.
-
IndrekV almost 3 yearsCorrect syntax for ignore is currently: globOptions: { ignore: ['**/LocalVideoDemo.jsx'], }
-
Sabari Krishnan M about 2 yearsCould you please elaborate, how to use this plugin?
-
Dancrumb about 2 yearsPerhaps, what kind of elaboration beyond this answer and the documentation of the plugin are you looking for?