Web Development

Getting Started With Parcel – Next Generation Web App Bundler


If you’re a web developer you have most certainly made some experience with bundlers like Browserify or Webpack. Those web application bundlers help you to pack the assets of your web application (code, images, packages etc.) into bundles so that the application can be served easily.

Furthermore most bundlers are able to perform many more tasks when building a web application like post processing of code or structuring your application for supporting lazy loading.

However, today most developers struggle with the complicated configuration of bundlers like Webpack. Parcel, a web application bundler, which has been released a few weeks ago is here to solve the problem. The promise is that Parcel is a lot faster then Webpack or Browserify and that the bundler at the same time is requiring no configuration (in most cases).

Let’s take a closer look at Parcel and see how you can use Parcel in your next web development project.

Installation

The project’s website can be found at https://parceljs.org/:


From the start page of the website you can get an overview of the most important features of Parcel:

  • Blazing fast bundle times
    Parcel uses multiple worker processes to ensure that the compilation process is executed in parallel on multiple cores. Furthermore Parcel uses a caching mechanism for the file system.
  • Bundle all your assets
    Parcel offers out of the box support for common project assets like JS, CSS, HTML. You do not need to install any plugins to make sure that Parcel is adding those assets to the bundles.
  • Automatic transforms
    By default Parcel is performing code transformations using Babel, PostCSS and PostHTML.
  • Zero configuration code splitting
    Parcel is making sure that the project code is split across multiple bundles if not all assets are needed initially. By using this code splitting approach not all assets needs to load at once and the user of the web application will experience a faster load. Code splitting is done by default, no extra configuration is needed.
  • Hot module replacement
    Parcel is watching for code changes and replaces modules automatically in the browser if needed.
  • Friendly error logging

To install Parcel you need to perform the following steps.

First install Parcel globally on your system by using NPM or Yarn.

Using Yarn you need to execute the following command:

$ yarn global add parcel-bundler

Using NPM you need instead execute the following command:

$ npm install -g parcel-bundler

Having installed Parcel on your system successfully we can now make use of Parcel in a new web project.

Initiating A New Project With Parcel

To initiate a new project let’s create a new empty project folder, change into that folder and execute one of the following commands:

With Yarn:

$ yarn init -y

With NPM:

$ npm init -y

This creates a new package.json file in your project directory.

To add an entry point for our application let’s add a new file index.html in the project directory and insert the following HTML code into that file:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Parcel Demo 01</title>
</head>
<body>
    <div id="message"></div>
    <script src="./app.js"></script>
</body>
</html>

This is just a simple HTML structure. In the body section of you can find two elements: a div element with id message and a script element to include the JavaScript file app.js.

The file app.js is not existing yet, so let’s create this new file in the project directory and insert the following line of code:

document.getElementById('message').innerText = "Hello World!";

This line of JS code is inserting the text “Hello World” into the div element with id message, so that the text should become visible in the browser.

Now let’s start up the development web server by using the following command:

$ parcel index.html

The web server is starting up on port 1234 and if you open up URL http://localhost:1234 in the browser you should be able to see the following output:

You can now update any part of the code (e.g. change the message text) and you’ll see the output in the browser being updated automatically.

If you now take a look into the project folder you’ll notice that two new folders have been created by Parcel:

The .cache folder contains the Cache content which is used by Parcel. The dist folder contains the output of Parcel and the content of that folder is served by the web server.

Inside the the dist folder you can see that for our application one JS bundle has been created.

Adding A Module To The Project

Let’s extend the sample project by creating a new JS module. Parcel supports both, CommonJS and ES6 module syntax. In the following example the ES6 syntax is used. If you want to use the CommonJS syntax instead you can do so without needing to change any configuration.

Add a new empty file lib.js to the project and insert the following JavaScript code:

export function square(x) {
    return x * x;
}

This is exporting the function square from the lib module, so that you can add the corresponding import statement in app.js:

import { square } from './lib';

You we can make use of that function in app.js:

document.getElementById('message').innerText = "The Square of 2 is " + square(2);

The output now changes to the following:

The new module has been added to the bundle that was created by Parcel automatically.

If you need to add dependencies to your project, that’s also no problem and Parcel will add the needed dependencies to the bundles as well.

E.g. add the jQuery library to the sample project by executing the following command in the project directory:

$ npm install jquery --save

You can now include jQuery by using the corresponding import statement and extend the example in file app.js with the code you can see in the following:

import { square } from './lib';
import $ from 'jquery';

let i = 2;

function setMessageText(msg) {
    $('#message').text(msg);
}

setMessageText("The Square of " + i + " is " + square(i));

$('#message').click(() => {
    i++;
    setMessageText("The Square of " + i + " is " + square(i));
})

Now the user is able to click on the message text and increment the input value by one. The square of that value is updated as well.

The jQuery has been added to the Parcel bundle without anything to do manually.

Adding CSS and SCSS Assets

Of course Parcel takes care of your CSS and SCSS assets. Those assets are automatically recognized and added to the bundle which is created for your project. You need to import CSS assets in a JavaScript or HTML file.

E.g. add a new file styles.css to your project directory, insert the following CSS code:

body {
    background-color: powderblue;
}
#message {
    color: blue;
    font-size: 3em;
    text-align: center;
}

and make sure that styles.css is included in index.html by added the following link element to the head section:

<link rel="stylesheet" href="styles.css">

The output in the browser should then change to what you can see in the following:

If you want to use SCSS code instead you first need to add the node-sass package first:

$ npm install node-sass

Then add a new file styles.scss to the project and insert for example the following SCSS code:

$messagecolor: blue;
$bgcolor: powderblue;

body {
    background-color: $bgcolor;
}
#message {
    color: $messagecolor;
    font-size: 3em;
    text-align: center;
}

And import that file in any JS file, e.g. in app.js with the corresponding import statement:

import './styles.scss';

The result in the browser should be the same as seen before.

Applying Transformations

Like many other bundlers Parcel is able to apply transformations to assets when building. Out of the box Parcel has already support for many common transforms and transpilers built in. Here are some examples:

  • Transform JavaScript using Babel
  • Transform CSS using PostCSS
  • Transform HTML using PostHTML

Parcel automatically runs those types of transformations when the corresponding module is installed and a small configuration file for the transformation (e.g. .babelrc) is available.

In the following exampel we’ll discover how to use Babel to transform JavaScript and JSX code by setting up a React project with Parcel.

Example: Setting Up A React Project With Parcel

Getting started with React has always been a difficult task with Webpack. Initiating a new React project required to add a lot of Webpack configuration to the project first. To make things easier it has been possible to use Create React App (https://github.com/facebookincubator/create-react-app) to initiate a new React project and generating the needed Webpack configuration automatically. However, this disadvantage of the Create React App approach is that it hides the complexity of the build configuration. This only works for small applications. If your application grows and you have further requirements for the build process you need to deal with the complex configuration anyway.

Using Parcel makes setting up a React project much more easier because there is nearly no configuration required.

$ mkdir react-parcel
$ cd react-parcel
$ npm init -y

Next add the following dependencies to the project:

$ npm install --save react
$ npm install --save react-dom
$ npm install --save-dev babel-preset-react
$ npm install --save-dev babel-preset-env

In order to tell Parcel that we’re using ES6 and JSX syntax in our project we need to add a new file .babelrc and include the following minimal configuration for Babel:

{
  "presets": ["env", "react"]
}

Next let’s create a simple React app by adding two new files two the project: index.html and app.js.

First insert the following code in index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>React Parcel Demo</title>
    </head>
    <body>
        <div id="app"></div>
        <script src="app.js"></script>
    </body>
</html>

Next add the implementation of the React component in app.js:

import React from "react";
import ReactDOM from "react-dom";

class HelloMessage extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

var mount = document.getElementById("app");
ReactDOM.render(<HelloMessage name="Sebastian" />, mount);

Now we’re ready to start up the React application by simply typing in the following command:

$ parcel index.html

and you should be able to see the application running in the browser:

Building For Production

If you want to build your project for production you can use the following command:

$ parcel build index.html

This command creates a dist sub folder where the generated output is stored. You can then use the content of this folder to deploy the application.

You can also specific the folder which should be used for outputting the production build by using command option -d in the following way:

$ parcel build index.html -d build/output

The production build process uses minification in order to decrease the bundle size.

ONLINE COURSE: The Complete JavaScript Course

Check out the great The Complete JavaScript Course: Build a Real-World Project.

The Complete JavaScript Course

  • Master JavaScript with the most complete JavaScript course on the market! Includes projects, challenges, final exam, ES6
  • You will go all the way from JavaScript beginner to advanced JavaScript developer.
  • You will gain a deep and true understanding of how JavaScript works behind the scenes.

Go To Course


Using and writing about best practices and latest technologies in web design & development is my passion.

    View Comments
    There are currently no comments.

    *