Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ module.exports = {
exclude: ['*.test.js'],
// Root directory (optional)
root: __dirname,
// Don't remove unused files automatically
remove: false,
}),
],
};
Expand All @@ -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

Expand Down
27 changes: 27 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const { searchFiles } = require('./lib/utils');

Expand All @@ -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) {
Expand All @@ -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);
};
Expand Down Expand Up @@ -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;
Expand Down