Install Bootstrap 4 using Node JS and Gulp

The Quickest way to Install Bootstrap 4

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Then, you include the necessary Javascript includes just before the closing </body> tag:

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

And that’s it. You’re now able to write HTML and harness the power of Bootstrap 4.

In this course, however, we will not use this method. We’re going to set up a more robust development environment and use the Sass version of Bootstrap 4.

Trending posts:

Installing Bootstrap 4 with a Package Manager like Node Package Manager

npm -v

It should provide you with a version number. If so, you’re ready to proceed by creating a new folder and installing Bootstrap 4.

mkdir newproject
cd newproject

Here we’ve created a new folder and we’re hopping into it. Now, let’s type npm init to create a package.json file:

npm init
<!--
This utility will walk you through creating a package.json file.            
It only covers the most common items, and tries to guess sensible defaults. 
                                                                            
See `npm help json` for definitive documentation on these fields            
and exactly what they do.                                                   
                                                                            
Use `npm install <pkg> --save` afterwards to install a package and          
save it as a dependency in the package.json file.                           
                                                                            
Press ^C at any time to quit.                                               
name: (gamelayout-pre)                                                      
version: (1.0.0)                                                            
description:                                                                
entry point: (index.js)                                                     
test command:                                                               
git repository:                                                             
keywords:                                                                   
author:                                                                     
license: (ISC)                                                              
About to write to C:\Users\gary\code\gamelayout\package.json:           
                                                                            
{                                                                           
  "name": "gamelayout",                                                 
  "version": "1.0.0",                                                       
  "description": "",                                                        
  "main": "index.js",                                                       
  "scripts": {                                                              
    "test": "echo \"Error: no test specified\" && exit 1"                   
  },                                                                        
  "author": "",                                                             
  "license": "ISC"                                                          
}                                                                           
                                                                            
                                                                            
Is this ok? (yes)  
-->        

Upon entering the npm init command, you will be prompted with the above screen. Just hit the enter key through all of the questions.

The package.json file this command creates serves as a configuration for your project. When we install Bootstrap 4 for instance, it will add the package name along with the version to this file. That way, in the future, if you need to install this project on another environment, you can run npm install and it will download all of the necessary packages based on this file.

Now, let’s install Bootstrap 4 with the npm install command:

npm install bootstrap --save

Note: At the time of writing this tutorial, bootstrap is currently in version 4.3. If you’re reading this at a later date and this version number has changed, notify me in the comments and I will update this tutorial.

Once this command is finished downloading and installing Bootstrap 4, there will be a new folder called node_modules within our project folder.

Inside, it will contain 3 folders:

  1. /bootstrap which contains the CSS and Sass version of our files.
  2. /jquery which is used by Bootstrap in various components.
  3. /tether which is a library for element positioning.

Each of these folders must be added to our project, but we don’t currently have a project to work with. Let’s remedy that.

Creating the Development Environment

We already have a project with Bootstrap integrated. Let’s create a more robust environment that we can use while we work on our Bootstrap 4 project.

In the project root folder, create a new folder called src. Inside this folder, create the following folder structure:

/src
   /assets
   /css
   /js
   /scss
  • /assets will contain our graphics. To access the assets you will need to follow along with this tutorial and this course, please visit the course page and download the project files.
  • /css this is the folder where the compiled CSS will reside.
  • /js this will house the minified bootstrap, tether and jquery files.
  • /scss this is where our custom Sass will reside.

Inside of the /src folder, create a new file called index.html and paste the following contents:

<!DOCTYPE html>
<html class="no-js" lang="en">
    <head>
        <title>AWESOME-GAME ///</title>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:400,800">
        <link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="/css/bootstrap.css">
        <link rel="stylesheet" href="/css/style.css">
    </head>

    <body>

        <!-- YOUR CONTENT HERE -->

        <script src="/js/jquery.min.js"></script>
        <script src="/js/popper.min.js"></script>
        <script src="/js/bootstrap.min.js"></script>
    </body>
</html>

After saving, if you were to visit this file in the browser, you would be met with a bunch of errors. There’s currently nothing in the /css and /js folders, which we will solve momentarily.

You may also notice two other link elements that are referencing a Raleway Google font, and FontAwesome.

For our project, we’re going to use Raleway as it’s my personal favorite, and also FontAwesome for a few icons.

Next, create a style.scss file inside of the /src/scss folder. Paste the following Sass inside of it:

$bg-color: blue;

body {
    background: $bg-color;
}

Using Gulp with Bootstrap 4

Gulp is a javascript task runner which will help us solve the empty folder issue, along with sass compiling and live browser reloading.

To get started, we first have to install Gulp with NPM and a few other packages.

In the command prompt, enter the following command to install Gulp. Adding ā€œ-gā€ flag ensures that the Gulp is globally available for any project.

npm install gulp

or

npm install gulp -g

To verify that Gulp has been installed successfully, enter the following command to display the Gulp version.

gulp -v
gulp version

Create gulpfile.js file

In the console within the project folder, type:

var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var sass = require('gulp-sass');

We first create variables that import the packages that we installed. 

Beneath this, we have to create a series of tasks which will define our gulpfile. Each task has a specific purpose based on the needs of our project.

So, we need to run sass on our Bootstrap 4 files to convert them to regular css files, right? Let’s create a task for that. 

Update our gulpefile.js :

var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var sass = require('gulp-sass');

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return gulp.src(['node_modules/bootstrap/scss/bootstrap.scss', 'src/scss/*.scss'])
.pipe(sass())
.pipe(gulp.dest("src/css"))
.pipe(browserSync.stream());
});

We create a task called sass, and inside of it, we have to tell it the src of these sass files. If you only had 1 sass file, you could omit the array brackets, but we have 2 so we keep them. We first take the bootstrap.scss file in the node_modules folder, and then any * .scss file inside of our /src/scss folder.

Then we use the pipe method to pass in our sass variable. This is where it transforms the sass files to regular CSS.

Then we use gulp.dest to designate the folder in which these new css files will be placed.

And then finally we use browserSync.stream() to notify the browser.

Install browserSync

npm i browser-sync --save 

Now, we also need another task for handling the required javascript files.

Update our gulpefile.js :

var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var sass = require('gulp-sass');

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return gulp.src(['node_modules/bootstrap/scss/bootstrap.scss', 'src/scss/*.scss'])
.pipe(sass())
.pipe(gulp.dest("src/css"))
.pipe(browserSync.stream());
});

// Move the javascript files into our /src/js folder
gulp.task('js', function() {
return gulp.src(['node_modules/bootstrap/dist/js/bootstrap.min.js', 'node_modules/jquery/dist/jquery.min.js', 'node_modules/popper.js/dist/popper.min.js'])
.pipe(gulp.dest("src/js"))
.pipe(browserSync.stream());
});

We create a task called js and simply move the three required javascript files into oursrc/js folder. Simple enough.

Let’s create a serve task and a default task. So once again update your gulpfile.js:

var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var sass = require('gulp-sass');

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return gulp.src(['node_modules/bootstrap/scss/bootstrap.scss', 'src/scss/*.scss'])
.pipe(sass())
.pipe(gulp.dest("src/css"))
.pipe(browserSync.stream());
});

// Move the javascript files into our /src/js folder
gulp.task('js', function() {
return gulp.src(['node_modules/bootstrap/dist/js/bootstrap.min.js', 'node_modules/jquery/dist/jquery.min.js', 'node_modules/popper.js/dist/popper.min.js'])
.pipe(gulp.dest("src/js"))
.pipe(browserSync.stream());
});

// Static Server + watching scss/html files
gulp.task('serve', gulp.series( 'sass', function() {

browserSync.init({
server: "./src" 
});

gulp.watch(['node_modules/bootstrap/scss/bootstrap.scss', 'src/scss/*.scss'], gulp.series('sass'));
gulp.watch("src/*.html").on('change', browserSync.reload);
}));

gulp.task('default',gulp.series('js','serve'));

The serve task passess the sass task that we created earlier. Along with it, we use browserSync.init to designate a folder for the static server to access in the browser. So that we can see the changes without reloading browser.

We use gulp.watch function to watch our HTML and SCSS files for changes. The browser will reload via browser-sync upon changes.

That’s our gulpfile.js!

Now we have our gulpfile ready to run. But, before running gulp function we need to add jquery and popper jquery to our project as Bootstrap 4 requires jquery to run smooth.

To install jquery run:

npm install jquery

To install the popper js run:

npm install popper.js --save

Now we have all the files for our project installed and we can run gulpfile.js to start developing our app.

On the command line, run:

gulp

This will load a browser at http://localhost:3000 and the background should be entirely blue.

If you visit the CSS, and JS folders within the /src folder, you will see they’re now populated with the files that are referenced in our index.html.

Now you’re ready to begin developing and learning how to use Bootstrap 4! In the next lesson, you will learn how to make sass-specific customizations when working with Bootstrap 4.

Possible errors during gulp setup

There may be chances for errors during the gulp file setup. We have shared the possible errors below.

Local gulp not found in your_project_path

Install gulp locally inside your project:

npm install gulp

Cannot find module ‘gulp-sass’

Run:

npm install --save gulp-sass

or

npm install -g gulp-sass

gulp command not found

The npm modules such as gulp are not installed to the path. Thus are not found when you run them in the CMD.

If gulp has been installed globally, you can use the process below:

My Computer > Properties > Advanced Settings

gulp command not found

Click on Environment Variables

gulp file not found node js

Now the Environment Variables screen appears. Click new user variable by clicking New

  1. Create an environmental variable with the name NODE_PATH
  2. Set the variable value to: %AppData%\npm\node_modules or %AppData%\npm
  3. Close CMD, and Re-Open to get the new ENV variables

Click OK and don’t forget to reopen cmd to update all variables.

In most of the cases, this should fix all if you still getting the same error then there is a chance of you have forgotten to install the gulp-cli package:

To install gulp-cli package run:

npm install -g gulp-cli

Error: Missing binding

Your node version sometimes messes up some of the npm module paths and they try using a version, different than the current one. To overcome this problem run either:

npm rebuild node-sass

or

npm rebuild node-sass --force

All issues should be fixed now. There is no chance for errors if you follow all steps carefully. But, if you met up with errors don’t worry, this is a common thing in development stages even small spelling mistakes can bring you a headache. If you are unable to find a solution here then do comment below and i will share a solution as soon as i can.

Related threads:

Follow TechBiriyani on FacebookTwitter to get all the latest updates.

Founder
View posts

A passionate blogger and a tech enthusiast who is always keen and awaiting to know about fully fledged new technologies who's currently using Zenfone 3 as a part of daily routine. You can spot me @ #facebook, #twitter & #Google +

Leave a Comment