In Front-End Development - 3 months ago

Continuous deployment using Gulp and Netlify

In this article, we will set up continuous deployment for a basic Gulp project using Netlify.

Introduction

Being a lazy programmer, I constantly think of ways to automate my development workflow so that I can catch up on my Netflix programmes. (I'm only at Season 2 of Black Mirror.)

Any toolkit or service that offers maximum returns with minimal work is a win in my book. 

We will explore one such service today.

Netlify is essentially a Software As A Service (SaaS) that allows any developer to deploy their static websites effortlessly.

It is a robust all-in-one development workflow solution with built-in Continuous Deployment, Atomic deploys, 1 click HTTPS, CDN, integration with Git repositories and so on.

Requirements

Initial Setup

  1. Install Node.js. Node.js comes with npm aka Node Package Manager and is required to install our Gulp packages.
  2. Install Gulp and the Gulp CLI.
$ npm install gulp-cli -g
$ npm install gulp -D

 

  1. Create a gulpfile.js and index.html in our project root folder.
$ touch gulpfile.js index.html

 

  1. Copy the following starter HTML and paste it into index.html.
<!DOCTYPE html>
<html lang="en">
<head>
  <title>A Netlify Gulp Demo</title>
  <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">
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col text-center p-5">
        <h1>Hello World!</h1>
        <p>A Simple Netlify Demo.</p>
      </div>
    </div>
  </div>
</body>
</html>

 

  1. Create a package.json file. This file will contain a list of our project dependencies.
$ npm init

 

  1. Install the following gulp dependencies required for this project.
$ npm install gulp-connect gulp-open

 

  1. Copy the following code and paste into gulpfile.js
const { watch, series, parallel, src, dest, gulp } = require('gulp');
const connect = require('gulp-connect'); // Runs a local webserver
const open = require('gulp-open'); // Opens a URL in a web browser

// Launch Chrome web browser
// https://www.npmjs.com/package/gulp-open
function openBrowser(done) {
  var options = {
    uri: 'http://localhost:8080'
  };
  return src('./')
  .pipe(open(options));
  done();
}

// Gulp plugin to run a webserver (with LiveReload)
// https://www.npmjs.com/package/gulp-connect
function server(done) {
  return connect.server({
    root: './',
    port: 8080,
    debug: true,
  });
  done();
}

// Default Gulp command
exports.default = series(openBrowser, server);

 

This simple script starts a local development server and launches a browser to preview our website.

Let's test it out by running the following command.

$ gulp

 

See how to automate your development workflow using Gulp.

Git ready

Now that our set up is ready, it is time to push our code to GitHub.

  1. Sign in to your Github account.
  2. Click on the plus sign at the top and select "New repository".

 

  1. Give your repository a name and an optional description. Remember to create a .gitignore file and exclude the node_modules directory from future commits. Pushing the entire node_modules folder to your repository is an extremely bad idea.
  2. Follow the instructions to push the code to the new repository.

Time to automate

  1. Sign in to Netlify with your Github credentials.
  2. Click on "GitHub".

 

  1. Authorise using your GitHub credentials.

 

  1. Click on "New Site From Git".

 

  1. Click on "GitHub" followed by"Configure Netlify on GitHub" to select your repository.

 

  1. Set the different options and finish the installation by clicking on the big green "Install" button.

 

  1. Back to the main window, click the repository that you wish to integrate with Netlify.

 

  1. On the next screen, we will leave the "Build command" and "Publish directory" fields blank for this demo.
  2. Click on the "Deploy site" button and Netlify will start the build process.

After the site has deployed, you can preview it by visiting https://your-netlify-site-id.netlify.com from the browser.

To test the continuous deployment process, make some changes to index.html, save it and push to GitHub.

Whenever Netlify detects new code pushes to the repository, it will trigger a build process and deploy to the staging site.

Obtain an npm token

In a real-world scenario, we would have additional npm dependencies for our application.

In order for Netlify to install the dependencies, we would need to give it access by creating an authentication token.

  1. Sign in to your npm account.
  2. Click on your profile link at the top and click on "Tokens".

 

  1. On the next screen, generate a token by clicking on the "Create New Token" button.
  2. Copy the token ID and store it somewhere. We'll need it for the next step.
  3. Create a .npmrc file at the root folder and paste the following into it.
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

 

  1. Go back to Netlify overview and click on "Site settings".

 

  1. Click on "Build & deploy."
  2. Scroll down to Build environment variables and click on "Edit variables".
  3. Enter NPM_Token for the key field and your npm Token ID in the value field.

Setting the npm token in an environment variable ensures that it remains secured and contained within our Netlify application. Exposing this value in the wild would again be a very bad idea because we are committing our codes to a public git repository.

The Netlify CLI

Wouldn't it be nice if we could deploy and preview our site using the command line instead of through the Netlify Admin UI? Well, we can!

 

Netlify provides a CLI tool with lots of useful commands that we can run.

  1. Install the Netlify CLI.
$ npm install netlify-cli -g

To see the commands available, run $ netlify help

  1. Link our project folder to our Netlify site. (Select the first option. > Use current git remote URL)
$ netlify link

 

  1. Run the following command to deploy the website.
$ netlify deploy --prod

Turbo boost the process using Gulp

Replace the existing code in gulpfile.js with the following.

const { watch, series, parallel, src, dest, gulp } = require('gulp');
const connect = require('gulp-connect'); // Runs a local webserver
const open = require('gulp-open'); // Opens a URL in a web browser
const exec = require('child_process').exec; // run command-line programs from gulp
const execSync = require('child_process').execSync; // command-line reports

// Launch Chrome web browser
// https://www.npmjs.com/package/gulp-open
function openBrowser(done) {
  var options = {
    uri: 'http://localhost:8080'
  };
  return src('./')
  .pipe(open(options));
  done();
}

// Gulp plugin to run a webserver (with LiveReload)
// https://www.npmjs.com/package/gulp-connect
function server(done) {
  return connect.server({
    root: './',
    port: 8080,
    debug: true,
  });
  done();
}

// Commit and push files to Git
function git(done) {
  return exec('git add . && git commit -m "netlify deploy" && git push');
  done();
}

// Watch for netlify deployment
function netlify(done) {
  return new Promise(function(resolve, reject) {
      console.log(execSync('netlify watch').toString());
      resolve();
    });
}

// Preview Deployment
function netlifyOpen(done) {
  return exec('netlify open:site');
  done();
}

// Deploy command
exports.deploy = series(git, netlify, netlifyOpen);

// Default Gulp command
exports.default = series(openBrowser, server);

 

Deploy.

$ gulp deploy

 

With one single command, we've

  1. added all modified and deleted files.
  2. committed the files to GitHub with a default message.
  3. pushed the codes to GitHub.
  4. triggered a $ netlify watch command for notifications.
  5. launched a browser to preview the website after deployment has completed.

Conclusion

This was a simple demonstration of continuous deployment using Gulp and Netlify.

There are also advance features from Netlify like FunctionsIdentity and Forms that you can leverage for your website as well.

Netlify’s generous free tier option is more than enough for basic static website publishing, however, you can upgrade to their paid tiers anytime which provides additional benefits.

You can grab the files for this tutorial from the GitHub repository.

In the next article, we will explore Surge; another feature packed static web publishing platform.

Back to Netflix.


blog comments powered by Disqus