Import Bootstrap and Font-Awesome using Parcel JS

Introduction

In previous post, I talked about importing jQuery and jQuery UI modules in our JavaScript code using Parcel JS.

Today, I want to share that how to include bootstrap and font-awesome packages in our application. We will be continuing with the same code-base from previous post. However, I created a new branch (bootstrapimport), so all the changes we make today, will go into that new branch.

Setting the Scene

I have following HTML markup in index.html file of our web application.

As you can see that markup have some buttons with bootstrap classes and also an HTML tag for font-awesome icon.

I can run the application using npm run dev and following is the browser display:

So you can see that we do not have bootstrap styles and font-awesome icons yet in the web page.

For your reference following is the index.js file (this is same as from the previous post).

Install Bootstrap and font-awesome using npm

Lets install these packages using npm as shown below:

Bootstrap

Bootstrap depends on Popper. This means that you will have to make sure to add both of them:

npm install bootstrap
npm install @popperjs/core


and poppersjs as follows:

Font-awesome

Next, lets install font-awesome using following command:

npm install --save @fortawesome/fontawesome-free

Import Bootstrap and Font-awesome

With packages installed, we can update the index.js file with both references as shown below:

and now if we refresh the browser window, we can see that now we have styles and icon as expected:

Next, lets try the JavaScript functionality of Bootstrap. I added the following html to index.html page:

I also added the following code line to index.js file:

Now, when the browser refresh, we can see a new button on the page. However, notice the error in the console window. Also, button click wont do the popover changes.

It is because, we have not imported the corresponding JavaScript in our code.

Let’s add the following code to our index.js file:

Save the index.js file and refresh the browser, you’ll see that console error is gone and also, if we click the button, you will see a nice popover similar to below picture:

Bundling and Testing the Application

As we have done this in previous posts, we can create the dist folder for production purposes by running npm run build command and it will create a dist folder for deployment purposes

here is the build output:

You can download the source code from this git repository (branch: bootstrapimport).

Summary

In this post, we saw how to import and use bootstrap and font-awesome modules in our JavaScript code. We used Parcel JS as a bundler which makes it very easy to import these modules in our web application and it also manages the dependencies well when we bundle our application for deployment purposes.

Let me know, if you have some comments or questions. Till next time, Happy Coding.

My Recent Books