Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

remove-files-webpack-plugin

Amaimersion91.7kMIT1.5.0TypeScript support: included

A plugin for webpack that removes files and folders before and after compilation.

webpack, webpack-plugin, webpack-compilation, webpack-files, compilation, plugin, files, build-automation, clean, cleanup, clean-plugin, clean-webpack-plugin, clean-files-plugin, clean-files-webpack-plugin, remove, remove-plugin, remove-webpack-plugin, remove-files-plugin, remove-files-webpack-plugin, delete, delete-plugin, delete-webpack-plugin, delete-files-plugin, delete-files-webpack-plugin, вебпак, вебпак-автоматизация, вебпак-файлы, вебпак-компиляция, компиляция, удалить, удаление, очистка

readme

Removing of folders and files for Webpack

A plugin for webpack that removes files and folders before and after compilation.

Content

Installation

  • With npm:

    npm install remove-files-webpack-plugin
  • With yarn:

    yarn add remove-files-webpack-plugin

Support

The plugin works on any OS and webpack >= 2.2.0.

Usage

const RemovePlugin = require('remove-files-webpack-plugin');

module.exports = {
    plugins: [
        new RemovePlugin({
            before: {
                // parameters for "before normal compilation" stage.
            },
            watch: {
                // parameters for "before watch compilation" stage.
            },
            after: {
                // parameters for "after normal and watch compilation" stage.
            }
        })
    ]
};

Notes

Symbolic links (soft links) will be treated as ordinary files.

Notes for Windows users

Single backward slash

JavaScript uses it for escaping. If you want to use backward slash, then use double backward slash. Example: C:\\Windows\\System32\\cmd.exe. By the way, single forward slashes are also supported.

Segment separator

All paths that you get or see from the plugin will contain platform-specific segment separator (i.e. slash): \\ on Windows and / on POSIX. So, for example, even if you passed folders or files with / as separator, TestObject.method will give you a path with \\ as segment separator.

Per-drive working directory

From Node.js documentation:

On Windows Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For example, path.resolve('c:\\') can potentially return a different result than path.resolve('c:'). For more information, see this MSDN page.

Parameters

Name Type Default Namespace Description
root string . All A root directory.
Not absolute paths will be appended to this.
Defaults to where package.json and node_modules are located.
include string[] [] All A folders or files for removing.
exclude string[] [] All A folders or files for excluding.
test TestObject[] [] All A folders for testing.
TestObject.folder string Required All A path to the folder (relative to root).
TestObject.method (absolutePath: string) => boolean Required All A method that accepts an item path (root + folderPath + fileName) and
returns value that indicates should this item be removed or not.
TestObject.recursive boolean false All Apply this method to all items in subdirectories.
beforeRemove (
absoluteFoldersPaths: string[],
absoluteFilesPaths: string[]
) => boolean
undefined All If specified, will be called before removing.
Absolute paths of folders and files that
will be removed will be passed into this function.
If returned value is true,
then remove process will be canceled.
Will be not called if items for removing
not found, emulate: true or skipFirstBuild: true.
afterRemove (
absoluteFoldersPaths: string[],
absoluteFilesPaths: string[]
) => void
undefined All If specified, will be called after removing.
Absolute paths of folders and files
that have been removed will be passed into this function.
Will be not called if emulate: true or skipFirstBuild: true.
trash boolean false All Move folders and files to the trash (recycle bin) instead of permanent removing.
It is an async operation and you won't be able to control an execution chain along with other webpack plugins!
afterRemove callback behavior is undefined (it can be executed before, during or after actual execution).
Requires Windows 8+, macOS 10.12+ or Linux.
log boolean true All Print messages of "info" level
(example: "Which folders or files have been removed").
logWarning boolean true All Print messages of "warning" level
(example: "An items for removing not found").
logError boolean false All Print messages of "error" level
(example: "No such file or directory").
logDebug boolean false All Print messages of "debug" level
(used for debugging).
emulate boolean false All Emulate remove process.
Print which folders and files will be removed
without actually removing them.
Ignores log parameter.
allowRootAndOutside boolean false All Allow removing of root directory or outside root directory.
It is kind of safe mode.
Don't turn it on if you don't know
what you actually do!
readWebpackConfiguration boolean false All Change parameters based on webpack configuration.
Following webpack parameters are supported: stats (controls logging).
These webpack parameters have priority over the plugin parameters.
See webpack documentation for more - https://webpack.js.org/configuration
skipFirstBuild boolean false watch First build will be skipped.
beforeForFirstBuild boolean false watch For first build before parameters will be applied,
for subsequent builds watch parameters will be applied.

How to set

You can pass these parameters into any of the following keys: before, watch or after. Each key is optional, but at least one should be specified.

  • before – executes once before "normal" compilation.
  • watch – executes every time before "watch" compilation.
  • after – executes once after "normal" compilation and every time after "watch" compilation.

Namespace

"Namespace" means where particular parameter will be applied. For example, "All" means particular parameter will work in any key (before, watch, after), watch means particular parameter will work only in watch key.

Compilation modes

  • "normal" compilation means full compilation.
  • "watch" compilation means first build is a full compilation and subsequent builds is a short rebuilds of changed files.

Examples

new RemovePlugin({
    /**
     * Before compilation permanently removes
     * entire `./dist` folder.
     */
    before: {
        include: [
            './dist'
        ]
    }
})
new RemovePlugin({
    /**
     * Every time before "watch" compilation
     * permanently removes `./dist/js/entry.js` file.
     */
    watch: {
        include: [
            './dist/js/entry.js'
        ]
    }
})
new RemovePlugin({
    /**
     * After compilation moves both
     * `./dist/manifest.json` file and
     * `./dist/maps` folder to the trash.
     */
    after: {
        root: './dist',
        include: [
            'manifest.json',
            'maps'
        ],
        trash: true
    }
})
new RemovePlugin({
    /**
     * Before compilation permanently removes both
     * `./dist/manifest.json` file and `./dist/maps` folder.
     * Log only works for warnings and errors.
     */
    before: {
        include: [
            'dist/manifest.json',
            './dist/maps'
        ],
        log: false,
        logWarning: true,
        logError: true,
        logDebug: false
    }
})
new RemovePlugin({
    /**
     * After compilation permanently removes
     * all maps files in `./dist/styles` folder and
     * all subfolders (e.g. `./dist/styles/header`).
     */
    after: {
        test: [
            {
                folder: 'dist/styles',
                method: (absoluteItemPath) => {
                    return new RegExp(/\.map$/, 'm').test(absoluteItemPath);
                },
                recursive: true
            }
        ]
    }
})
new RemovePlugin({
    /**
     * After compilation:
     * - permanently removes all css maps in `./dist/styles` folder.
     * - permanently removes all js maps in `./dist/scripts` folder and
     * all subfolders (e.g. `./dist/scripts/header`).
     */
    after: {
        root: './dist',
        test: [
            {
                folder: './styles',
                method: (absoluteItemPath) => {
                    return new RegExp(/\.css\.map$/, 'm').test(absoluteItemPath);
                }
            },
            {
                folder: './scripts',
                method: (absoluteItemPath) => {
                    return new RegExp(/\.js\.map$/, 'm').test(absoluteItemPath);
                },
                recursive: true
            }
        ]
    }
})
new RemovePlugin({
    /**
     * Before compilation permanently removes all
     * folders, subfolders and files from `./dist/maps`
     * except `./dist/maps/main.map.js` file.
     */
    before: {
        root: './dist'
        /**
         * You should do like this
         * instead of `include: ['./maps']`.
         */
        test: [
            {
                folder: './maps',
                method: () => true,
                recursive: true
            }
        ],
        exclude: [
            './maps/main.map.js'
        ]
    },

    /**
     * After compilation permanently removes
     * all css maps in `./dist/styles` folder
     * except `popup.css.map` file.
     */
    after: {
        test: [
            {
                folder: 'dist/styles',
                method: (absoluteItemPath) => {
                    return new RegExp(/\.css\.map$/, 'm').test(absoluteItemPath);
                }
            }
        ],
        exclude: [
            'dist/styles/popup.css.map'
        ]
    }
})
new RemovePlugin({
    /**
     * Before "normal" compilation permanently
     * removes entire `./dist` folder.
     */
    before: {
        include: [
            './dist'
        ]
    },

    /**
     * Every time before compilation in "watch"
     * mode (`webpack --watch`) permanently removes JS files
     * with hash in the name (like "entry-vqlr39sdvl12.js").
     */
    watch: {
        test: [
            {
                folder: './dist/js',
                method: (absPath) => new RegExp(/(.*)-([^-\\\/]+)\.js/).test(absPath)
            }
        ]
    },

    /**
     * Once after "normal" compilation or every time
     * after "watch" compilation moves `./dist/log.txt`
     * file to the trash.
     */
    after: {
        include: [
            './dist/log.txt'
        ],
        trash: true
    }
})
new RemovePlugin({
    /**
     * Before compilation emulates remove process
     * for a file that is outside of the root directory.
     * That file will be moved to the trash in case of
     * not emulation.
     */
    before: {
        root: '.', // "D:\\remove-files-webpack-plugin-master"
        include: [
            "C:\\Desktop\\test.txt"
        ],
        trash: true,
        emulate: true,
        allowRootAndOutside: true
    }
})
new RemovePlugin({
    /**
     * After compilation grabs all files from
     * all subdirectories and decides should
     * remove process be continued or not.
     * If removed process is continued,
     * then logs results with custom logger.
     */
    after: {
        root: './dist',
        test: [
            {
                folder: '.',
                method: () => true,
                recursive: true
            }
        ],
        beforeRemove: (absoluteFoldersPaths, absoluteFilesPaths) => {
            // cancel removing if there at least one folder.
            if (absoluteFoldersPaths.length) {
                return true;
            }

            // cancel removing if there at least one `.txt` file.
            for (const item of absoluteFilesPaths) {
                if (item.includes('.txt')) {
                    return true;
                }
            }
        },
        afterRemove: (absoluteFoldersPaths, absoluteFilesPaths) => {
            // replacing plugin logger with custom logger.
            console.log('Successfully removed:');
            console.log(`Folders – [${absoluteFoldersPaths}]`);
            console.log(`Files – [${absoluteFilesPaths}]`);
        },
        log: false
    }
})

Version naming

This project uses following structure for version naming: <MAJOR RELEASE>.<BREAKING CHANGES>.<NOT BREAKING CHANGES>.

Contribution

Feel free to use issues. Pull requests are also always welcome!

License

MIT.

changelog

1.5.0 (December 13, 2021)

Changed

  • Symbolic links (soft links) will be treated as ordinary files and thus will be removed. Earlier behavior was silent ignore. #40
  • TestObject.method will be called for symbolic links.
  • Upgrade trash dependency to 7.2.0 version.

1.4.5 (June 1, 2021)

Changed

  • Upgrade @types/webpack dependency to 5.28.0 version.
  • Upgrade trash dependency to 7.1.1 version.

1.4.4 (September 3, 2020)

Improved

  • Documentation for trash parameter. #32

Changed

  • Upgrade @types/webpack dependency to 4.41.22 version.

1.4.3 (June 7, 2020)

Added

  • Information about version naming in README.
  • New feature: readWebpackConfiguration. Part of plugin configuration may be controlled with global webpack configuration. #29

1.4.2 (May 15, 2020)

Improved

  • Little refactoring (related to English language, not information) of documentation and log messages. #27

1.4.1 (April 25, 2020)

Improved

  • Documentation for beforeRemove, afterRemove parameters.

Added

  • Namespace documentation for every parameter.
  • New feature: beforeForFirstBuild. For first build before parameters will be applied, for subsequent builds watch parameters will be applied. Works only in watch key. #25
  • New feature: skipFirstBuild. First build will be skipped. Works only in watch key.

Changed

  • Upgrade @types/webpack dependency to 4.41.12 version.

1.4.0 (February 27, 2020)

Added

  • New key: watch. Parameters of that key will be applied in "watch" mode. Parameters of before key will no longer be applied in "watch" mode. So, make sure your current configuration still have expected behavior. #22

Fixed

  • A bug when old include and old exclude were mixed with new include and exclude in "watch" mode. It had no effect, because the plugin checks an items for existence before removing. Just strange messages were presented in warning log.

1.3.0 (February 24, 2020)

Improved

  • Stability, performance and quality.
  • Documentation and description.
  • Pretty printing of folders and files that have been removed.

Added

  • New features: beforeRemove and afterRemove parameters. See readme for documentation.

Changed

  • trash parameter is false by default.
  • TestObject.method supports testing for folders. Ensure that behavior of your current tests remain unchanged.

Fixed

  • A bug when safety of removal could have been incorrectly determined in specific cases.
  • A bug when "unnecessary" folders and files could have been incorrectly excluded in specific cases.
  • A bug when exclude could not work as expected in specific cases.

1.2.2 (January 19, 2020)

Fixed

  • A bug when root path was escaped incorrectly. #16

1.2.1 (December 25, 2019)

Added

  • Type definitions. #13

1.2.0 (December 23, 2019)

Improved

  • Stability and quality.
  • Documentation and description.

Added

  • New feature: trash. Now you can remove your items in a trash (recycle bin).
  • New features: logWarning, logError and logDebug. Now you can control logging of different levels. #10

Changed

  • Text of log messages.

Fixed

  • A bug when safety of removal was incorrectly determined. #7
  • A bug when the plugin not worked in --watch mode. #9
  • A bug when a path could be incorrectly changed for pretty printing.
  • A bug when unnecessary items could be cropped incorrectly.

1.1.3 (May 10, 2019)

Fixed

  • Fix a bug when folder path in warning message was undefined. #5.

1.1.2 (April 4, 2019)

Fixed

  • Fix compatibility with webpack 3.x #3.

1.1.1 (March 20, 2019)

Nothing changed. Had to change the version because of problems with npm. See changelog for 1.1.0 version.

1.1.0 (March 20, 2019)

Fixed

  • No longer necessary set __dirname to root in order to specify an actual root directory.
  • If you not set include and test parameters, there will be no more message An items for removing not found..

Changed

  • Plugin name that used in terminal now contains a version.
  • If allowRootAndOutside option is off, then in terminal a paths will be printed without the root.
  • Improved cross-platform properties.
  • Improved readability of log messages.

Added

  • Add a link to README to error message which appears in case you do not specify neither before nor after parameters.
  • Add a warning message if allowRootAndOutside option is on and if there is unsafe removing.

1.0.0 (June 5, 2018)

Initial release.