DEV Community

Cover image for HTML includes with Gulp.js
Caio Jhonny
Caio Jhonny

Posted on • Edited on

HTML includes with Gulp.js

How beautiful it would be if HTML had the option of including repeating blocks, right?

Using Gulp.js and some packages, we can make that dream come true!

This tutorial uses Gulp 4.0. This is the most recent stable version and the current default on npm.

Let's get started!

First of all let's create our project and the html files that will be used for this tutorial.



mkdir myproject && cd myproject
touch index.html header.html footer.html


Enter fullscreen mode Exit fullscreen mode

header.html and footer.html will be the files that we will include in our index.html.

Our index.html example



<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Gulp Html Include Boilerplate</title>
  </head>
  <body>
    <!-- Content -->
    <section>
      <h1>Hello world</h1>
    </section>
  </body>
</html>


Enter fullscreen mode Exit fullscreen mode

Our include files example

header.html


<!-- Header -->
<header>
  My Header
</header>


Enter fullscreen mode Exit fullscreen mode
footer.html


<!-- Footer -->
<footer>
  My Footer
</footer>


Enter fullscreen mode Exit fullscreen mode

Add packages

For this tutorial we will use Yarn as a package manager. (You can use npm if you prefer)

Starting a new project



yarn init


Enter fullscreen mode Exit fullscreen mode

Install the gulp-file-include plugin



yarn add gulp gulp-file-include -D


Enter fullscreen mode Exit fullscreen mode

gulpfile

Let's create our gulpfile to be able to create our tasks with Gulp



touch gulpfile.js


Enter fullscreen mode Exit fullscreen mode

Import gulp and gulp-file-include. We will also create a variable paths to define the path of our source and the destination path (where the static html files will be after the build).



const gulp        = require('gulp');
const fileinclude = require('gulp-file-include');

const paths = {
  scripts: {
    src: './',
    dest: './build/'
  }
};


Enter fullscreen mode Exit fullscreen mode

In our gulpfile.js file we will create a task function that will be responsible for including our html files and returning static files.



async function includeHTML(){
  return gulp.src([
    '*.html',
    '!header.html', // ignore
    '!footer.html' // ignore
    ])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest(paths.scripts.dest));
}


Enter fullscreen mode Exit fullscreen mode

For now we will set our function as default and we will test our script.



exports.default = includeHTML;


Enter fullscreen mode Exit fullscreen mode

Add the include tags to index.html



@@include('./header.html')

<!-- Content -->
<section>
  <h1>Hello world</h1>
</section>

@@include('./footer.html')


Enter fullscreen mode Exit fullscreen mode

Run the gulp command



yarn gulp


Enter fullscreen mode Exit fullscreen mode

The build folder will be created with our index.html file inside

Alt Text

We can see the content of header.html and footer.html have been included into our index.html



<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Gulp Html Include Boilerplate</title>
  </head>
  <body>

    <!-- Header -->
    <header>
      My Header
    </header>

    <!-- Content -->
    <section>
      <h1>Hello world</h1>
    </section>

    <!-- Footer -->
    <footer>
      My Footer
    </footer>
  </body>
</html>


Enter fullscreen mode Exit fullscreen mode

But it can be a little tiring to run the gulp command every time we modify our files, let's automate this task.

Bonus #1: Live Browser Reload

Add the browser-sync plugin



yarn add browser-sync -D


Enter fullscreen mode Exit fullscreen mode

Let's load the plugin and the watch/series methods inside our gulpfile.js



const server = require('browser-sync').create();
const { watch, series } = require('gulp');


Enter fullscreen mode Exit fullscreen mode

Add the reload function



// Reload Server
async function reload() {
  server.reload();
}


Enter fullscreen mode Exit fullscreen mode

If you have assets you will need this function to move them to the build folder.



// Copy assets after build
async function copyAssets() {
  gulp.src(['assets/**/*'])
    .pipe(gulp.dest(paths.scripts.dest));
}


Enter fullscreen mode Exit fullscreen mode

Let's create a function that includes our files and then reload the server.



// Build files html and reload server
async function buildAndReload() {
  await includeHTML();
  await copyAssets();
  reload();
}


Enter fullscreen mode Exit fullscreen mode

We will need our default gulp function, so we will have to rename the current one to:



exports.includeHTML = includeHTML;


Enter fullscreen mode Exit fullscreen mode

Now that we have all the functions, we will recreate the default function of our gulp script by inserting the following code:



exports.default = async function() {
  // Init serve files from the build folder
  server.init({
    server: {
      baseDir: paths.scripts.dest
    }
  });
  // Build and reload at the first time
  buildAndReload();
  // Watch task
  watch(["*.html","assets/**/*"], series(buildAndReload));
};


Enter fullscreen mode Exit fullscreen mode

Our final gulpfile.js file



const gulp        = require('gulp');
const fileinclude = require('gulp-file-include');
const server = require('browser-sync').create();
const { watch, series } = require('gulp');

const paths = {
  scripts: {
    src: './',
    dest: './build/'
  }
};

// Reload Server
async function reload() {
  server.reload();
}

// Copy assets after build
async function copyAssets() {
  gulp.src(['assets/**/*'])
    .pipe(gulp.dest(paths.scripts.dest));
}

// Build files html and reload server
async function buildAndReload() {
  await includeHTML();
  await copyAssets();
  reload();
}

async function includeHTML(){
  return gulp.src([
    '*.html',
    '!header.html', // ignore
    '!footer.html' // ignore
    ])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest(paths.scripts.dest));
}
exports.includeHTML = includeHTML;

exports.default = async function() {
  // Init serve files from the build folder
  server.init({
    server: {
      baseDir: paths.scripts.dest
    }
  });
  // Build and reload at the first time
  buildAndReload();
  // Watch task
  watch(["*.html","assets/**/*"], series(buildAndReload));
};


Enter fullscreen mode Exit fullscreen mode

Start your server in localhost and see the autoreload working. 🎉🎉🎉



yarn gulp


Enter fullscreen mode Exit fullscreen mode

Alt Text

Each time the file is saved, Gulp follow the flow of tasks making the files and refreshing the page.

Bonus #2: Sass Compiler

Let's create our scss file inside the sass folder



mkdir sass && touch sass/style.scss


Enter fullscreen mode Exit fullscreen mode

Add the gulp-sass plugin



yarn add node-sass gulp-sass -D


Enter fullscreen mode Exit fullscreen mode

Open the gulpfile.js file and insert the following lines to load the plugin



const sass = require('gulp-sass');
sass.compiler = require('node-sass');


Enter fullscreen mode Exit fullscreen mode

Now let's create the function that will help us to compile scss files into css:



// Sass compiler
async function compileSass() {
  gulp.src('./sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./assets/css'));
}


Enter fullscreen mode Exit fullscreen mode

The destination folder will be "/assets/css" because later our build will move all the contents of assets folder to the build folder.

Let's add a watch to compile our css each time we make a modification inside the scss file

Before the buildAndReload watch add:



// Watch Sass task
watch('./sass/**/*.scss',  series(compileSass));


Enter fullscreen mode Exit fullscreen mode

We must not forget to load the css file that will be loaded after the build



<link rel="stylesheet" type="text/css" href="css/style.css">


Enter fullscreen mode Exit fullscreen mode

And now, just start the gulp and make changes to the scss file:



yarn gulp


Enter fullscreen mode Exit fullscreen mode

Change the color of the body
Style.scss file

And... 💥
Screenshot

Link to Code

You can find the final code here

Hope it's helpful some of you 🙂

Top comments (7)

Collapse
 
dohahelmy profile image
Doha Helmy • Edited

What if I needed to add a task to compile SCSS files? how to include it exactly in gulpfile?
And how about building html files in structured folders, how to do that?

Collapse
 
caiojhonny profile image
Caio Jhonny

Hi Doha, I updated the post with instructions to compile sass!
By the way of structured folders, could you give me an example?

Collapse
 
alisonpinheiro profile image
Alison Pinheiro

Thanks for the article. Helped a lot

Collapse
 
caiojhonny profile image
Caio Jhonny

Fico feliz meu caro =)

Collapse
 
sh4rov profile image
Anatoly Sharov

Thank you for the article! Good luck!

Collapse
 
sh4rov profile image
Anatoly Sharov

How can I use this plugin to make a starter template that would be included for each page and could pass a different title for the page?

Collapse
 
caiojhonny profile image
Caio Jhonny

I believe that you will not be able to extend a base html template with this plugin, just include new blocks within an html file