DEV Community

Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

Tools and modern workflow for front-end developers

Recently different tools and workflows have emerged in order to make the front-end development process easier — I call one of these tools a build tool. In this tutorial, we will explore what build tools are and how to use them. We’ll look at NPM scripts, grunt, gulp and also webpack. We will also talk about how to choose which build tool to use based on your project needs.

Prerequisites

Most build tools are built on top of NODE and NPM. In this tutorial, basic knowledge of NPM is assumed but not required as we will also do an introduction to NPM. This tutorial does require a basic knowledge of HTML , CSS , and JavaScript.

NPM

NPM (Node package manager) is a JavaScript package manager that comes pre-installed with Node.js even though no Node.js skills are needed to use it. NPM’S primary function is to run a simple task like browser-synching, loading in libraries and style sheets dynamically from your package.json file. NPM installs a node_modules folder which then lets you run even more commands from the various installed packages. Any native CLI task can be done within the script using the right objects. Let's see some examples.

Usage

By default NPM comes pre-installed with NODE. So no need to install it differently. To use npm scripts all you have to do is initialize it. Create a new folder called npm_test then initialize NPM to create a package.json file. In your terminal type npm init then follow the prompt. Once that is done you should now see a package.json file inside your projects folder. The file should look like this:

{
      "name": "npm_tests",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
Enter fullscreen mode Exit fullscreen mode

As you can see, index.js is defined as the main script otherwise known as the entry point to our application. We need to create that file and also tell NPM how to start our app. First, create a blank file called index.js then update the scripts object in your package.json file to look like this:

"scripts": {
        "start": "node index.js"
     },
Enter fullscreen mode Exit fullscreen mode

This tells node that whenever we type the command npm start in the terminal, it should start up the index.js file. Inside your index.js file let's put a simple log message. Add the following code:

console.log('This is index.js')
Enter fullscreen mode Exit fullscreen mode

Now in your terminal type npm start and you should see the following output:

$ npm start
    > npm_tests@1.0.0 start /home/user/frontend/npm_tests
    > This is index.js
Enter fullscreen mode Exit fullscreen mode

Now although this example isn’t very robust. Later on, when we talk about other build tools and we will see how we can use npm scripts to perform other useful commands like installing dependencies, testing, etc.

Yarn

Yarn (Yarn Package Manager) is another JavaScript package manager created by Facebook. Over time it has been regarded as a faster and more reliable alternative to NPM because they have similar syntax and functionality. Yarn also installs packages from the NPM Registry so any NPM Package can also be installed with Yarn. Yarn has a different philosophy for managing packages. Let's take a look at some of them.

Usage

Yarn and NPM perform basically the same functions. Though they are similar in functions, they both have a different syntax. To find out how to install and use yarn follow the instructions on this page.

NPM or Yarn? Many have argued (and tests have proven) that Yarn is faster than npm, however, a great majority still use npm and most of the build tools we will talk about support npm by default. However, choosing a tool to use is mainly a function of the developers and project needs. Always be sure to pick a tool that best fits your projects needs.

Grunt

Grunt is a JavaScript task runner built on top of Node.Js and NPM. Its primary function is to optimize and help you reduce all repetitive tasks in your project like loading in JavaScript resources, style sheets, linting and debugging. Since GRUNT is built on top of NPM it is initialized with a package.json file but the tasks are defined in a Grunt.js file.

N/B: **'G'** in **Grunt.js** must be capitalized. Let's see how to use it to enhance our development:

Usage

To use grunt we first need to install it. In your terminal type npm install -g grunt. This will install grunt globally on your machine. Next, create a folder called grunt_test and initialize a package.json file. In your terminal type npm init and follow the prompt to create the file. Now your package.json file should look like this:

{
      "name": "grunt_test",
      "version": "1.0.0",
      "description": "",
      "main": "app.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
Enter fullscreen mode Exit fullscreen mode

Next, we need to install Grunt as a dependency. In your terminal type npm install --save grunt. That command will install grunt as a dependency and your package.json file will now look like this:

{
      "name": "grunt_test",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "grunt": "^1.0.3"
      }
    }
Enter fullscreen mode Exit fullscreen mode

Now that grunt is installed, let's use it. Create an empty gruntfile.js file. For us to use this file we need to set a goal, let's assume we have several files with codes in it and we want to compile them into one. For that, we need to use a plugin (plugins are pieces of code that add extra functionality to a tool). To achieve our goal, we will use a plugin called grunt-contrib-concat. To install the plugin type this in your terminal:

npm install grunt-contrib-concat --save-dev
Enter fullscreen mode Exit fullscreen mode

Now let’s put it in action. Create a folder called js, then create two files main1.js and main2.js and add this code:

/** this is main1.js **/
Enter fullscreen mode Exit fullscreen mode

Do the same for main2.js . Now in your gruntfile.js file add the following lines of code to it:

module.exports = function(grunt){

      grunt.initConfig({
       concat: {
        dist: {
          src: ['js/main1.js', 'js/main2.js'],
          dest: 'dist/js/built.js',
         },
        },
      });

      grunt.loadNpmTasks('grunt-contrib-concat');
    };
Enter fullscreen mode Exit fullscreen mode

This task is instructing grunt to copy the files from main1.js and main2.js to a folder/file called dist/built.js. Though this file is not already created grunt will automatically create it for us. In your terminal type grunt concat:

$ grunt concat
    Running "concat:dist" (concat) task
    Done
Enter fullscreen mode Exit fullscreen mode

Now you will see a new folder has been created dist/built.js:

/** this is main one */
    /** this is main two */
Enter fullscreen mode Exit fullscreen mode

This shows it added the contents of the two files together. This is powerful when you have a lot of JavaScript styles it will help optimize your website by compiling all of the code into just one file. There are a lot of other functions and uses of grunt, you can find them here.

Gulp

Gulp.js is yet another JavaScript task runner built on top of Node.js and NPM. Its primary function is to help you reduce all repetitive tasks in your project. Gulp is a front-end build system, so it doesn’t matter what front-end technology is used (Vue, React or Angular) it still works and performs optimally. It is also managed with a package.json file and has built-in support for various plugins that help in performing various tasks.

Usage

Gulp is built on top of node strings and processes data in the form of pipelines. Create a folder called gulp_test and initialize a package.json file. In your terminal type npm init and follow the prompt to initialize the file. Your package.json will now look like this:

{
      "name": "gulp_test",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
Enter fullscreen mode Exit fullscreen mode

To use gulp, we must install it as a project dependency. In your terminal type npm install --save-dev gulp. This will save it as a project dependency and your package.json file will now look like this:

{
      "name": "gulp_test",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "gulp": "^4.0.0"
      }
    }
Enter fullscreen mode Exit fullscreen mode

To create tasks we have to create a file called gulpfile.js and add code to it. Gulp has four top-level functions:

  • gulp.task  — sets a task for gulp to run
  • gulp.src  — tells gulp the file to use
  • gulp.dest  — tells gulp where to output the files
  • gulp.watch  — tells gulp to watch for updates

Let’s create dummy HTML. First, create a src folder and add the two files to it. index.html and test.html then add the following code to it:

<html>
        <head>
            <title>Gulp Test</title>
        </head>
        <body>
            <h2>This is for a test</h2>
        </body>
    </html>
Enter fullscreen mode Exit fullscreen mode

Let’s set some tasks. In your gulp.js file add the following lines of code:

const gulp = require('gulp');

    gulp.task('compileHtml', function(done){
      gulp.src('src/*.html')
      .pipe(gulp.dest('build'));
      done();
    });
Enter fullscreen mode Exit fullscreen mode

This command tells gulp to copy all the files from the src directory to a build directory. We created a function compileHtml, and that is what we will refer to when we want to run our tasks. In your terminal type gulp compileHTml. Now see a build folder has been created with the files in it. Next, let’s use a gulp plugin to minify our Javascript. First, we need to install the plugin. For a list of gulp plugins check here.

First, let’s create a folder called js and create a test file in it test.js. Next, we need to install a plugin called uglify to help us minify our files. In the terminal type npm install --save-dev gulp-uglify. This will install it as a dependency in our project. Now in your gulpfile.js update the code to this:

const gulp = require('gulp');
    const uglify = require('gulp-uglify');


    gulp.task('compileHtml', function(done){
      gulp.src('src/*.html')
      .pipe(gulp.dest('build'));
      done();
    });

    gulp.task('minify', function(done){
      gulp.src('src/js/*.html')
      .pipe(uglify())
      .pipe(gulp.dest('build/js'));
      done();
    });
Enter fullscreen mode Exit fullscreen mode

Webpack

Webpack is a front-end build tool. More accurately, it is defined as a Module Bundler. Webpack’s functionality goes beyond just converting different modules into static assets. Webpack makes it easy to bundle code, transpile all older JS code into ES6 , load development dependencies, run automated tasks and manage your project. With Webpack you can load custom files or files installed by NPM. The basic functionality of Webpack can be extended into more complex ones by using plugins and loaders css sass jsx CoffeeScript are examples of common Webpack loaders.

Usage

To use Webpack, we must first install it. We can install it through the terminal by typing npm install -g Webpack. This command will install Webpack globally on your machine. Next, let’s create a folder to work with. Create a folder webpacktest and initialize a package.json file. In your terminal type npm init and follow the prompts to create the file. Now the package.json file should look like this:

{
      "name": "webpacktest",
      "version": "1.0.0",
      "description": "",
      "main": "app.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
Enter fullscreen mode Exit fullscreen mode

Now that we have it setup let’s do something with it. Let’s say we want to use JQuery library in our new project, here’s how we can do it. First, we need to install JQuery. In your terminal type npm install --save jquery. If that is successful your package.json file will now look like this:

{
      "name": "webpacktest",
      "version": "1.0.0",
      "description": "",
      "main": "app.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "jquery": "^3.3.1"
      }
    }
Enter fullscreen mode Exit fullscreen mode

You can see JQuery has been installed as a dependency. Now for us to use it we need to create files. First, let’s create an HTML file we will load in our browser. Create an index.html file and add the following lines of code to it:

<html>
        <head>
            <title>WebPack Test</title>
        </head>
        <body>

            <script src="bundle.js"></script>
        </body>
    </html>
Enter fullscreen mode Exit fullscreen mode

You can see we called a file namedbundle.js even though it has not been created yet. When we run our Webpack command, Webpack will automatically compile all of the code we tell it to into that file. Now create an app.js file and add the following lines of code:

let $ = require('jquery');

     $('body').append("<h1>Hey there! This is JQUERY</h1>");
Enter fullscreen mode Exit fullscreen mode

Here we are requiring JQuery in our project then we are using the append JQuery function to add data to our page. To see this, type webpack --mode=development app.js -o bundle.js. Once done, open your index.html file in the browser and you will see the following:

This means that Webpack successfully bundled the code and imported the JQuery library for us to use. You can already see how beneficial this is as if we had to import ten dependencies Webpack makes it possible for us to add all to just one file instead of individual files. Let’s use useful data. Create a books.js file and add the following lines of code to it:

let books = [
     { name: "Hey there my name is awesome"},
     { name: "The mythical man month"},
     { name: "Please don't make me think"}
    ]

    module.exports = books;
Enter fullscreen mode Exit fullscreen mode

Next, update your app.js to look like this:

let $ = require('jquery');
    let books = require('./books.js');

    $.each(books, function(key, value){
      $('body').append("<h1>"+ books[key].name +"</h1>");
    })
Enter fullscreen mode Exit fullscreen mode

Here we import the books from the books.js file and dynamically add it to our HTML page using special JQuery functions. Now if you run the command webpack --mode=development app.js -o bundle.js you will see this on your page:

In your terminal type webpack --mode=development app.js -o bundle.js --watch . Now any change you make Webpack automatically watches and updates the bundle.js file. Finally, let’s see how we can add styles to our page. For us to use CSS or SASS in Webpack we must use a loader. Let’s install it. In your terminal type npm install --save-dev css-loader style-loader. Your package.json file will now look like this:

{
      "name": "webpacktest",
      "version": "1.0.0",
      "description": "",
      "main": "app.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "jquery": "^3.3.1"
      },
      "devDependencies": {
        "css-loader": "^2.0.1",
        "style-loader": "^0.23.1"
      }
    }
Enter fullscreen mode Exit fullscreen mode

You can see both loaders have been installed as dev dependencies for us to use them. Let’s create a style sheet and add basic styles to it. Create a styles.css file and add the following lines of code to it:

body {
      background: yellow;
    }
Enter fullscreen mode Exit fullscreen mode

Now update your app.js file to look like this:

require('!style-loader!css-loader!./styles.css');
    let $ = require('jquery');
    let books = require('./books.js');

    $.each(books, function(key, value){
      $('body').append("<h1>"+ books[key].name +"</h1>");
    })
Enter fullscreen mode Exit fullscreen mode

Now since Webpack is in watch-mode, refresh your browser and you will see this:

Now we’ve seen how to use Webpack and how it can help development. There are still a lot of Webpack commands, techniques, and plugins to explore, you can find them here.

Conclusion

In this tutorial, we talked about different build tools and how they can help improve our development. All of these tools are great and are fit for certain use cases. However, try not to spend so much time thinking about which tool to use. Just define your projects needs then try to use a tool that best fits that need and is not too difficult to set up and get up to speed with. Thanks. Happy coding!


Plug: LogRocket, a DVR for web apps

https://logrocket.com/signup/

LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single page apps.

Try it for free.


The post Tools and modern workflow for front-end developers appeared first on LogRocket Blog.

Top comments (0)