Modern Web Apps with Babel and Parcel

December 16, 2018

Babel allows us to use new JavaScript features that are not quite supported yet by browsers today - even if they are still in proposal stage. Parcel on the other hand is a great zero-config bundler that’s a delight to use.

In this article, I’ll be explaining how to setup a modern web app project with Babel and Parcel hand-in-hand.

Install Parcel

Installing Parcel is easy - just run npm i parcel-bundler inside an npm project and that’s it!As a “zero-config” bundler, Parcel is very opinionated (in a good way) and does not allow users to tweak the build configs.

That being said, there are many Parcel plugins that adds optional goodies to our project. My favorite ones are parcel-plugin-sw-precache (service worker) and parcel-plugin-static-files-copy (copies static asset files to the final builds). Some of the plugins support some minimalistic one-liner configurations, which are usually put inside package.json.

After installing parcel-bundler inside our project, we need to add some build scripts to tell Parcel where the entry point of the project is. Usually it’s the root index.html file.

{
  // ...
  "scripts": {
    "start": "parcel ./src/index.html",
    "build": "parcel build ./src/index.html"
  },
  // ...
}

Parcel then reads that HTML file when build is started, finds out which JS file is referenced inside the HTML, then continues the bundling process from there.

Using Future JS Features Today with Babel

One awesome thing about Parcel is that not only the bundler itself is zero-config - it parses all the import statements in our JS files and runs npm install in the background for us! Actually not only this, it reads Babel’s config file and installs the Babel plugins we needed automatically too.

Some of the new (proposal) JS features that I can’t live without are class attributes (to “never” use constructors again), decorators (to use MobX and co.). I am also writing most of my JS code for React, so my typical Babel config looks like this:

{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    "@babel/plugin-transform-react-jsx",
    "@babel/plugin-transform-runtime"
  ]
}

Save this config file as .babelrc inside the project root, run npm start or yarn start again then Parcel will automatically set up everything for us!

Setting up modern JavaScript projects is much easier nowadays!