cross platform "rm" command
If you do not concern about 'rm/del not found' console.log, here is the short and simple solution, no additional dependencies are required, rm works on Mac and Linux, del works on Windows:
{
"scripts": {
"build": "(rm bundles/*.js || del bundles/*.js) && webpack",
},
}
Take a look at shelljs:
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
And further to shelljs/shx, which provides the following example:
{
"scripts": {
"clean": "shx rm -rf build dist && shx echo Done"
}
}
An alternative:
You may also want to take a look at Gulp or Grunt, both so called Task Runners. Gulp has gulp-clean and Grunt has grunt-contrib-clean. Both aim to delete folders and/or files.
Let's take Grunt for example:
- Add the Grunt CLI with
npm i -g grunt-cli
to your system - Add the needed packages to your project with
npm i --save-dev grunt grunt-contrib-clean
- Create a file named
gruntfile.js
- Add the following lines:
module.exports = (grunt) => { 'use strict'; grunt.initConfig({ clean: ['bundles'], }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.registerTask('default', ['clean']); };
- Update your script
"build": "grunt && webpack"
The npm package rimraf is available for command-line usage in scripts
.
First install locally into your project:
$ npm install --save-dev rimraf
Then update the build
script in your package.json file:
"scripts": {
"prebuild": "rimraf bundles/*.js",
"build": "webpack"
}
The rimraf command (named after rm -rf
) deletes the files.
Documentation:
https://www.npmjs.com/package/rimraf#cli
rimraf is a well established project with over 3,000 4,000 ⭐s on GitHub.