Lesson Monday

We've explored several tools that help streamline back-end development. Now let's add some tools to help us quickly develop the front-end of our application. Fortunately, we can use Webpack to manage both, and the process for adding front-end dependencies is the same. In this lesson we'll show how simple it is to add jQuery and Bootstrap to our projects with Webpack.

jQuery

To add jQuery to our project we need to do two things:

  1. Install jQuery as a dependency.
  2. Import jQuery into the JS files you would like to use it in.

We don't even need to touch our webpack.config.js file! To install the npm package for jQuery, use this command:

$ npm install jquery --save

Notice that we are using the --save flag and not the --save-dev. This lets npm know that we want to use this package for production and development. You'll see that a new section has been created in package.json called dependencies and jquery has been added to it. Now that we have a node module for jquery installed, if we want to use jQuery in a file, we simply need to import it into that file:

src/main.js
import $ from 'jquery';

Don't forget to remove the scripts tag for jQuery from index.html

And that's all we need to do to get jQuery into our projects using Webpack!

Bootstrap

Adding Bootstrap is also fairly simple. Since the full version of Bootstrap requires both js and css files, there are a few extra steps. Note that Bootstrap depends on jQuery and a library called Popper.js, so make sure you have jQuery and Popper.js installed properly first before installing Bootstrap. We'll assume that you followed along above and already have jQuery installed. Let's install Popper.js as a dependency using npm:

npm install popper.js --save

Now we're ready to add Bootstrap. We're going to use the same steps as we did above to install the js files for Bootstrap:

  1. Install Bootstrap as a dependency.
  2. Import Bootstrap into the JS files you would like to use it in.
$ npm install bootstrap --save

If we open up package.json we can see that both Popper.js and Bootstrap have been added to our list of dependencies:

package.json
{
  ...
  "dependencies": {
    "bootstrap": "^4.0.0",
    "jquery": "^3.3.1",
    "popper.js": "^1.14.0"
  }
  ...
}

Now all we need to do is import Bootstrap into main.js so that it will be included in our bundle:

src/main.js
import 'bootstrap';

That takes care of adding the js files for Bootstrap. Now we need to import the css files. We are going to work with the minified css for Bootstrap. If you would like to work with Bootstraps Sass files (not recommended if you are unfamiliar with Sass), check out the Importing Pre-Compiled Sass article of the Bootstrap documentation. To do that we simply add another import statement to main.js:

src/main.js
...
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

With these configurations in place, we're ready to start styling with Bootstrap!