The major frontend frameworks(libraries) like Angular, React, Vuejs are pre-configured with a bundler( webpack ) which helps build and bundle your assets/files into a single file and served in the browser. When using vanilla javascript, you can also use a bundler to do same. This is where Parcel comes in, which is a fast, zero-configuration web application bundler.
Parcel.js prides itself has been all about developers experience, saving developers time to do small tasks. For instance, if your app is running a parcel-bundler
in development, you don't need to kill your server to install a new package. Just import the package and Parcel will install it under the hood for you.
In this article, we will demonstrate how Parcel works with a simple project. To get started, ensure you have Node installed on your computer.
Let's create a folder(parcel-demo) to house our project and in that folder, create two files index.html
and index.js
. Open the folder in your code editor(I use VsCode ).
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parcel Demo</title>
</head>
<body>
<h1>This is a parcel demo</h1>
<script src="index.js"></script>
</body>
</html>
Create a third file called demo.js
and put the following code
demo.js
export function sayHello(name) {
return `Hello ${name}`
}
Import this inside the index.js
file as below
import { sayHello } from './demo';
sayHello('Dave');
Open the index.html
file in the browser, check the console and you will see error,
Uncaught SyntaxError: Cannot use import statement outside a module
Recall that this es6
which is not understood by the browser. This is where Parcel.js comes; to transpile the es6
and bundle our app via the entry index.html
file.
Let's install parcel.js
into our project.
Run yarn init -y
or npm init -y
in the root of your project to create the package.json
file.
To add Parcel
as a package to our project, run
yarn add parcel-bundler --dev
or npm install parcel-bundler --save-dev
. This installs parcel
as a dev dependency.
Open the package.json
created and add
"scripts": {
"dev": "parcel index.html",
"build": "parcel build index.html"
},
When you run yarn dev
or npm run dev
(visit http://localhost:1234/
to see the page), parcel bundles all our files and assets into a single file through the entry point of the app index.html
. Also, the error above disappears as parcel allows you to use es6
import statement. To run in production mode, use yarn build
or npm run build
.
Conclusion
We can see that Parcel gives the bundling effect as webpack does. It also has zero-config unlike webpack and other bundlers. Other features Parcel provides include Code Splitting and Hot Module Replacement . For more details, visit the Parceljs documentation to explore further.