diff --git a/README.md b/README.md index 6523154..81e3971 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ module.exports = { exclude: ['*.test.js'], // Root directory (optional) root: __dirname, + // Don't remove unused files automatically + remove: false, }), ], }; @@ -39,6 +41,7 @@ module.exports = { - `root` : root directory that will be use to display relative paths instead of absolute ones (see below) - `failOnUnused`: whether or not the build should fail if unused files are found (defaults to `false`) - `useGitIgnore`: whether or not to respect `.gitignore` file (defaults to `true`) +- `remove`: whether or not to remove unused files automatically (defaults to `false`) With root diff --git a/index.js b/index.js index 149bd2a..c1ab382 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,5 @@ const path = require('path'); +const fs = require('fs'); const chalk = require('chalk'); const { searchFiles } = require('./lib/utils'); @@ -8,6 +9,7 @@ function UnusedPlugin(options) { this.root = options.root; this.failOnUnused = options.failOnUnused || false; this.useGitIgnore = options.useGitIgnore || true; + this.remove = options.remove || false; } UnusedPlugin.prototype.apply = function apply(compiler) { @@ -23,6 +25,7 @@ UnusedPlugin.prototype.apply = function apply(compiler) { // Find unused source files .then(files => files.map(array => array.filter(file => !usedModules[file]))) .then(display.bind(this)) + .then(remove.bind(this)) .then(continueOrFail.bind(this, this.failOnUnused, compilation)) .then(callback); }; @@ -71,6 +74,30 @@ function display(filesByDirectory) { chalk.yellow(` • ${path.relative(directory, file)}\n`), )); }); + + return allFiles; +} + +function remove(allFiles) { + if (!allFiles.length) { + return []; + } + if (!this.remove) { + process.stdout.write(chalk.green('\n*** Unused Plugin ***\n\n')); + return allFiles; + } + let deleteCount = allFiles.length; + allFiles.forEach((file) => { + try { + fs.unlinkSync(file); + } catch (error) { + process.stdout.write( + chalk.red(`Error removing file ${path.relative(process.cwd(), file)}\n`), + ); + deleteCount -= 1; + } + }); + process.stdout.write(chalk.green(`\n🔥 ${deleteCount} files deleted.\n`)); process.stdout.write(chalk.green('\n*** Unused Plugin ***\n\n')); return allFiles;