How to clean (delete contents) folder with npm [closed]

I am trying to deploy a web project but before build it, I need to clear/delete the dist folder.

I could add a script that would run rm -rf dist/* but that would not work on Windows system.

Is there some npm package u other solution that allows deleting a folder with a command that works in every OS?


You can use rimraf: https://github.com/isaacs/rimraf.

Note that if you are using globs containing the globstar (**), you must double-quote them. Unix systems don't all support the globstar by default, but rimraf will expand them for you. Windows doesn't support single-quotes, so those can't be used. Remember that double-quotes must be escaped in JSON with a \.


Recently I was faced with the same challenge as you, and just like user Kevin Brown stated in a comment above, I was interested in a solution which wasn't just "use this npm package". So I'm throwing this out here hoping someone will find it useful.

So, what I did was taking some code I found in StackOverflow, putting it on a .js file, and binding it to an npm script in my package.json. In my case, the goal was to delete the "/out" folder, where .ts scripts were compiling to, but the possibilities are endless!

With this solution, you only need to start your app with "npm run cleanstart".

package.json

{
    "name": "my_app",
    "version": "1.0.0",
    "main": "main.js",
    "scripts": {
        "tsc": "tsc",
        "precleanstart": "node clean.js",
        "cleanstart": "npm start",
        "prestart": "npm run tsc",
        "start": "node out/main.js"
    },
    "dependencies": {
        "@babel/runtime": "^7.0.0-beta.54",
        "babel-runtime": "^6.26.0",
        "body-parser": "^1.18.3",
        "express": "^4.16.3",
        "typescript": "^3.0.3"
    }
}

clean.js

var fs = require('fs');

function deleteFolderRecursive(path) {
  if (fs.existsSync(path) && fs.lstatSync(path).isDirectory()) {
    fs.readdirSync(path).forEach(function(file, index){
      var curPath = path + "/" + file;

      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        deleteFolderRecursive(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });

    console.log(`Deleting directory "${path}"...`);
    fs.rmdirSync(path);
  }
};

console.log("Cleaning working tree...");

deleteFolderRecursive("./out");

console.log("Successfully cleaned working tree!");

npm install --save-dev del-cli 

"scripts": {
    "delete": "del-cli --force ../folder-to-delete"
}

notice "--force" when you want to delete a parent folder


I found this today:
npm i clean-webpack-plugin --save-dev

plugins: [
    ...
    new CleanWebpackPlugin(['dist'])
 ]

FYI: https://www.npmjs.com/package/clean-webpack-plugin