Javascript Workflow for Small Projects

Introduction

Today I thought I would write a quick post on how I’m setting up my Javascript for small client and personal projects.

TL;DR… I include vendor and module files in my main.js with a gulp package called gulp-include which concatenates, minifies, uglifies and outputs a file

Getting Started

First let me show you the basic JS structure of the project

|-- js
|   |-- modules
|   |    |-- nav.js
|   |    |-- modal.js
|   |    |-- hero.js
|   |-- main.js

|-- vendor
|   |-- jquery
|   |-- flickity

The goal here is to get the modules and vendor files to concatenate in to an output file called main.min.js - we can achieve this with Gulp.

To include our module and vendor files in to our main.js we have to declare them at the top of our file like this:

//=require ../vendor/jquery/jquery.js
//=require ./modules/nav.js

$('body').on('click', function() {
    $('nav').addClass('twerk');
});

So by writing the //=require comment with a path to our relevant directory we can reference our module and vendor files with gulp-include which then picks up and concatenates the file.

Below is our example Gulpfile.js which will build out our files.

// Require them packages
var gulp         = require('gulp');
var include       = require('gulp-include');
var uglify       = require('gulp-uglify');
var rename       = require("gulp-rename");

// Create the task
gulp.task('scripts', function() {
   gulp.src('js/main.js')
      .pipe(include())
      .pipe(uglify())
      .pipe(rename({
         suffix: ".min",
      }))
      .pipe(gulp.dest('js'));
});

This will grab the main.js file in the JS folder and include all your modules/vendor files, then uglify and rename the file to main.min.js and then last but not least output it in the same directory as the original main.js.

Fin

I hope this makes sense. I know there must be better and probably even simpler processes out there, which I’d love to hear about!

Thanks for reading 🤓

Further Reading