Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wipe dist/ directory before a build with Parcel

Tags:

parceljs

I have a very simple project set up to use Parcel as the bundler. It's just the basic example from their Getting Started guide.

For a single build everything works fine but I noticed that for every build the javascript code is compiled under a new hash. This can result in multiple JS hashes being created in the dist/ directory. Is there a way to clear everything from dist/ before every build so that it only contains the latest code?

like image 888
Valentin Avatar asked Jun 08 '19 12:06

Valentin


3 Answers

You can run rm -rf public/dist/* before running parcel build directly in package.json scripts

{ 
  // ...
  "scripts": {
    "build": "rm -rf public/dist/* && parcel build src/index.html --out-dir public/dist --public-url /dist/",
  }
  // ...
}
like image 164
OzzyCzech Avatar answered Oct 07 '22 01:10

OzzyCzech


You can delegate the clean up task to a singular script which task will be to wipe your output directory. Please note that using rm -rf is more error-prone than using a platform-agnostic package such as rimraf which will also executes without any issues in a Windows environment.

The steps are:

  1. npm i -D rimraf
  2. Then edit your package.json scripts key like shown below.
{ 
   "scripts": {
     "clean:output": "rimraf dist",
     "start": "npm run clean:output && parcel src/index.html",
     "build": "npm run clean:output && parcel build src/index.html",
  }
 
}

As an alterative, you can use a prescript for each of the scripts but I personally think it will make your scripts section hard to read. This approach is more flexible to changes. If you later decide to change the target output directory there is only one place you need to visit and change in the package.json file.

like image 7
denik1981 Avatar answered Oct 07 '22 03:10

denik1981


One option that requires little setup and is cross-platform would be to use a plugin like parcel-plugin-nuke-dist. Just install it and it will clear the dist/ dir before every build:

npm install parcel-plugin-nuke-dist --save-dev

NOTE: parcel-plugin-nuke-dist isn't compatible with Parcel v2, please see the other answers for alternatives

like image 6
Valentin Avatar answered Oct 07 '22 03:10

Valentin