18

What is the reason for running "rimraf dist" command in the build script in package.json file?

"scripts": { "build": "rimraf dist ..." }, 

4 Answers 4

26

The rimraf package which you will probably find in the devDependencies section of the package.json you have, is used to safely remove files and folders on all platforms (Unix and Windows).

When you have a build system, you want to also make sure you remove the output files before re-emitting the build output content (especially in case you have removed some files which are not needed anymore). You could go ahead and do:

"scripts": { "clean": "rm ./dist/* -Recurse -Force" } 

But that will work on Windows only, and sometimes will also give you problems due to issues around the use of *. On Unix the command would be different. In order to make things better, rimraf does the removal for you so you can simply invoke it in your scripts/clean section:

"scripts": { "clean": "rimraf dist" } 

This will ensure your package.json (your build system) to be cross-platform.

Sign up to request clarification or add additional context in comments.

2 Comments

I have also seen it being used in the scripts / prebuild section.
Is this still relevant these days with windows subsystem for linux?
5

rimraf
A rm -rf util for nodejs

$ rimraf dist removes the dist file or folder.
I guess the build script puts stuff inside the dist directory and wants to remove the old stuff from the last time you build it.

2 Comments

Why not just use rm -rf instead? I mean what do we get with rimraf that we do not get with rm -rf?
@TaranjeetSingh here is a good read on why not to use it: ashleysheridan.co.uk/blog/Why+You+Should+Not+Use+Rimraf
1

What actually needs to be known is what the script rimraf dist is doing, and that's simple it's cleaning out the dist folder to give you a clean start on what is assumed to be a web app or TypeScript app that requires some level compilation.

But, it isn't limited to that alone. Rimraf is a package that allows you the power of rm -rf ./dist which is specific to Linux OS. As suggested in the above comment this command will give you problems on Windows, especially when there is a directory that isn't empty or the file path becomes too long (very common with nested npm dependencies). Rimraf will bypass those exceptions as if you're running on Linux and this becomes a very powerful tool.

1 Comment

Good context, I also wondered why I shouldn't just use rm -rf as a command, but of course on Windows I have become so used to having gitbash installed and using bash as the default in web project terminals that Windows compatibility hadn't occurred to me.
0

To be sure that all old files are deleted from the folder before the script will compile the files.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.