Add Destroy Script 🔥💻 To package.json

deadlybyte

Carl Saunders

Posted on February 25, 2020

Add Destroy Script 🔥💻 To package.json

On rare occasions I find myself having to clean my development environment (i.e. delete the following folders - node_modules, build, coverage, etc). As this could include multiple folders, I decided the best approach was to create a script. I also hate typing the same commands over and over again, save those fingers!🖐️

I wanted a cross platform approach (works on both Linux and Windows), rimraf is the ideal candidate as it's an npm package that deletes folders recursively and works cross platform.

Why make the solution cross platform? So all developers that collaborate on the code base can benefit.

Now we could install rimraf globally, but we can't guarantee that another developer has this installed, which will result in the script failing when executed.

A cleaner approach is to have the dependency installed as a dev dependency. However, this will cause issues as rimraf will try to delete the node_modules folder where rimraf is currently executing from. Hence it would try and delete itself and fail.

So to resolve this issue, we can execute rimraf when we need to run it (one-off invocation without local installation) via the npx command. The npx command was introduced with npm 5.2.0 and later.

The Destroy Script 🔥

Below is an example of the destroy script, this will delete the node_modules, build and coverage folders and all their contents.

{
  "scripts": {
    "destroy": "npx rimraf node_modules build coverage",
  }
}
Enter fullscreen mode Exit fullscreen mode

Execute Destroy Script

The destroy script can be executed either by using npm or yarn.

npm run destroy
Enter fullscreen mode Exit fullscreen mode

Or

yarn destroy
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
deadlybyte
Carl Saunders

Posted on February 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related