The most frequently used frontend tools manual

    Introduction

    This manual contains a description of useful and the most frequently used front-end tools. The process of installing tools and the main points of working with them are described here.

    NPM

    Introduction

    Third-party libraries and plugins are often added during project development. As a result, developers need to search for the required dependency, download, unpack the archive and copy files to the project. Package managers help make this routine work automated.

    Package Manager is software that allows managing processes of installation, removal, configuration and update of various components.

    Attachment of third-party libraries by the package manager is replaced with a pair of commands in the terminal.

    NPM is one of the package managers used in frontend projects.

    npm (Node.js Package Manager) is the package manager that is part of Node.js. It is used to download packages from the cloud-based npm server or to download packages to this server.

    Official website

    https://www.npmjs.com/

    Start of work

    For installing npm it is needed to download and instal NodeJS (npm will be installed automatically): https://nodejs.org/en/.

    Implementation

    Packages installation

    Package is one or several JavaScript files representing some library or tool.The following command should be done for package installation:

    1. pm install <package name>

    The key -g is used for global package installation.The package with source codes is located in the directory node_modules/ after installation.

    Version check

    The following command is run to check the current version of npm:

    1. pm -v

    Configuration file adjustment

    The package.json file contains information about the application such as: name, version, dependencies, etc. Any directory containing this file is interpreted as a Node.js package.

    Example of package.json file:

    To create the package.json file, run the following command:

    1. pm init

    After that it is necessary to fill some information about the project.

    This file contains names and versions of all packages required in the project. Using npm install command, all packages of  package.json can be loaded.

    For installing some package and saving it automatically in package.json file, the following command is used:

    1. pm install <package name> --save-dev

    Alternatives

    Yarn

    Official website https://yarnpkg.com/lang/en/

    Yarn is a package manager jointly created by Facebook, Google, Exponent and Tilde. Its goal is solving a number of problems that the developers have faced during using npm:

    • packages installation was not enough fast and consistent;
    • security issues occurred, because npm allows packages to run code while installation.

    Bower

    Official website https://bower.io/

    Bower is a package management system on the client side. Its work depends on Node.js and npm. Bower system is meant to manage components that contain HTML, CSS, JavaScript, fonts and images. It contains functions for searching, downloading and installing packages. Bower.json manifest file is designed to manage packages in Bower.

    GulpJS

    Introduction

    Building is an integral part of any frontend project. Task managers are used for this task.

    Task manager is an application designed to automate project building and for other routine tasks that should be performed during the development process (code minimization, concatenation, launch of unit tests and much more). To do this, the developer writes instruction to task performance after creating a task-file. As a result, the project development is simplified.

    GulpJS is one of these task managers.

    GulpJS is a task manager for automatic performance of frequently used tasks, it is written in JavaScript. This software uses the command line to run tasks defined in Gulpfile file. It is created as a branch of Grunt project to take best practices out of it. It is distributed through the NPM package manager licensed under MIT.

    GulpJS differs from other task managers by better visibility and simplicity. It is also the fastest project builder.
    There are about 3000 plugins for Gulp by 2017.

    Official website

    http://gulpjs.com/

    Features

    • Creating web server and automatic page reload in browser during code saving, tracking changes in project files.
    • Using various JavaScript, CSS and HTML preprocessors (CoffeeScript, Less, Sass, Stylus, Jade, etc.).
    • Minifying CSS and JS code, and also optimizing and concatenating separate project files into one.
    • Creating vendor prefixes automatically for CSS (addings before CSS property name that browser manufacturers add for non-standard properties).
    • Managing files and folders within the project, such as creating, deleting, renaming.
    • Running and monitoring external commands execution of the operating system.
    • Working with images, such as compression, creating sprites, resizing (png, jpg, svg, etc.).
    • Deploying (sending to an external server) of the project via FTP, SFTP, etc.
    • Connecting and using an infinitely large number of Node.js and Gulp utilities, programs and plug-ins in the project.
    • Creating of various project maps and automating of other manual labor.

    Start of work

    NodeJS and npm should be installed in the system.

    Step 1: For a global installation of GulpJS using the npm batch manager, run the following command:

    1. pm install gulp -g

    Step 2: It should be installed for the following application:

    1. pm install --save-dev gulp

    Step 3: Next, the file gulpfile.js should be created in the root of the project (in this file building tasks are written).
    Load of additional plugins, that can be used for project building, is also done using npm by the following command:

    1. pm install <plugin name> --save-dev

    All installed plugins are located in  node_modules/ directory.

    Example gulpfile.js

    Implementation

    Step 1: First, gulp should be connected to the project. To perform this, in the file gulpfile.js the following line should be written:

    1. var gulp = require('gulp');

    Require() function allows connecting plugins from the node_modules/ directory.

    Step 2: Using gulp variable, tasks for project building can be created:

    1. gulp.task('exampleTask', function() {});

    The task  method takes two values: the name and the function with the task body. This instruction can be already performed. To do this, the following line should be written in the console:

    1. gulp exampleTask

     Basic Commands

    The more complex example of the instruction is given below:

    1. gulp.task('exampleTask', function () {
    2. return gulp.src('source-files')
    3. .pipe(plugin())
    4. .pipe(gulp.dest('folder'));
    5. });

    Commands used in this example:

    • gulp.src  - selection of source project files for plugin processing;
    • pipe(plugin()) - calling Gulp plugin for file processing;
    • pipe(gulp.dest('folder'))  - an output of the resulting file to the destination folder.

    Masks of files

    The gulp.src function takes a file mask as a value. Examples of masks:

    • ./  - the current directory;
    • ../  - the parent directory;
    • js/index.js - the file index.js in the js folder;
    • js/*.js - all files with js extension in js folder;
    • js/**/*.js  - all files with  js extension in js folder and its subdirectories;
    • !js/*.js - excluding files with js extension in js folder.

    Streams

    Using streams is one of the most important advantages of GulpJS.

    Streams allow transferring some data in sequence from one function to another, and each performs some actions with this data.

    The function gulp.src() creates a stream of objects representing files that are passed to it as a parameter. Next, using pipe functions, a pipeline is built, by which the stream of objects is transferred. The plugin, which in some way processes the stream of objects, is passed as a parameter to this function.

    Below there is an example of using streams. In this example, third-party plugins gulp-jshint and gulp-concat are used, which should be installed and connected to gulpfile.js.

    The function gulp.src takes files by the mask js/*.js. It starts JSHint and prints the result. Then it concatenates files and at the end stores the received file after concatenating in the dist/. directory.

    1. gulp.task('example', function () {
    2. return gulp.src('js/*.js')
    3. .pipe(jshint())
    4. .pipe(concat('index.js'))
    5. .pipe(gulp.dest('dist'));
    6. });

    Third-party plugins

    Let's consider an example of using third-party plugins. To do this, the instruction for js files concatenating is created:

    Step 1: First, you need to connect the plugin with require command:

    1. var concat = require('gulp-concat');

    Step 2: Then the task to concatenate the files with js extension located in  js/ directory should be created. Finally, the received file is placed in dist/js directory:

    1. gulp.task('concat', function () {
    2. return gulp.src('js/*.js')
    3. .pipe(concat('index.js'))
    4. .pipe(gulp.dest('dist/js'));
    5. });

    Step 3: Further this task can be done in the console:

    1. gulp concat

    Additional information

    Also the task that causes the execution of other tasks can be defined.

    1. gulp.task('build', ['html', 'css']);

    Plus, there is a watch method for watching changes in files:

    1. gulp.watch('file mask for watching',
    2. ['a task name, which is done during files changing']);

    A default task can be created in gulpfile.js :

    1. gulp.task('default', ['task1', 'task2']);

    This task is launched from the console by using the command:

    1. gulp

    Basic Plugins

    • gulp-autoprefixer - automatically sets prefixes to CSS properties;
    • gulp-browser-sync - creates a connection, then performs page auto-updating when client or even server files are changed;
    • gulp-uncss - for an optimization of CSS files. The plugin analyzes HTML code and finds all unused and duplicated styles;
    • gulp-csso - CSS minifier;gulp-htmlmin - a simple HTML-style minifier;
    • gulp-htmlhint - HTML validator;gulp-uglify - JavaScript minifier;
    • gulp-concat - files concatenation;
    • gulp-webserver - allows creating and running server;gulp-jshint  - checking JS code quality;
    • gulp-jasmine - running jasmine tests;
    • gulp-jsdoc - for generation of JSDoc documentation.

    The full list of Gulp plugins can be found here:

    http://gulpjs.com/plugins/ 

    Alternatives

    GruntJS

    https://gruntjs.com/ is an official website

    GruntJS is a task manager, like GulpJS, which allows automating routine tasks for developers related to code minification, code quality analysis, testing, and many others.

    Differences

    Unlike GulpJS, GruntJS does not use data streaming. Gruntfile (the configuration file in GruntJS) is less readable and it is harder to take it up than the configuration file in GulpJS. In addition, GruntJS is a slower assembler than Gulp.

    Jasmine

    Introduction

    Testing is part of the development process on any project. It allows verifying the code correctness and identifying situations where program behavior is incorrect, undesirable or doesn't conform to the specification. Each engineer checks whether some function works correctly during the development process. The easiest way to do this is to run the function and see a result. However, this approach is a very imperfect way of code testing . As a result, any moment that leads to malfunctioning can be missed and thus to an error. Automated testing is used to prevent such situations.

    Automated testing is the process of writing tests separately from the code, with the ability to run them at any time and check all important usage cases.

    One of the tools for testing JavaScript code is Jasmine.

    Jasmine is a BDD framework for testing JavaScript code, which borrowed many features from RSpec.

    Official website

    https://jasmine.github.io/

    Features

    • A support of asynchronous testing.
    • An ability to expose observers on different objects.

    Start of work

    To connect Jasmine to the project, download the library and connect the following files to the main HTML page:

    • lib/jasmine-*/jasmine.js - the framework itself;
    • lib/jasmine-*/jasmine-html.js - the presentation of results in HTML form;
    • lib/jasmine-*/jasmine.css - the appearance of the test result;
    • SpecRunner.html - the file that should be opened in a browser to run the tests.

    Synchronization with tools

    GulpJS

    Jasmine can be connected to the project build in GulpJS:

    Step 1: First, the plugin gulp-jasmine should be installed:

    1. pm install gulp-jasmine --save-dev

    Step 2: Then the plugin in the build file should be connected and tests starting task should be created:

    1. var jasmine = require('gulp-jasmine');
    2. gulp.task('jasmine', function() {
    3. gulp.src('tests files')
    4. .pipe(jasmine());
    5. });

    KarmaJS

    (the working process with this tool is described in detail at the end of the article)

    To connect Jasmine to KarmaJS the following steps should be done:

    Step 1: Install KarmaJS:

    1. pm install -g karma-cli

    Step 2: Install the plugins required to run tests written in Jasmine in Chrome and PhantomJS browsers:

    1. pm install karma-jasmine karma-chrome-launcher karma-phantomjs-launche

    Step 3: Install Jasmine:

    1. pm install -g jasmine

    Step 4: Connect plugins and set the path to tests in the karma configuration file.

    Implementation

    Keywords

    • describe - the definition of the test set;
    • it - test definition;
    • expect - defining the expectations, that are checked in the test.

    Describe and  it functions take two parameters: the first is the name, the second is the function with the code.

    An example of a basic test

    1. describe(“test suite name”, function () {
    2. it(“test name”, function () {
    3. expect(2+2).toBe(4);
    4. });
    5. });

    Results verifying methods

    • expect().toBe() - verifying variables for equality ('===');
    • expect().not.toBe() - verifying variables for equality ('! ==');
    • expect().toEqual() - verifying equality of variables and objects, including content;
    • expect().toBeDefined() - verifying existence;
    • expect().toBeUndefined() - verifying nonexistence;;
    • expect().toBeNull() - verifying value of the variable to null;
    • expect().toBeTruthy() - verifying validation;
    • expect().toBeFalsy() - verifying falsity;
    • expect().toBeLessThan() -verifying the value should be less than;
    • expect().toBeGreaterThan() - verifying the value should be bigger than;
    • expect().toBeCloseTo() - verifying the value should be close to a number;
    • expect().toMatch() - verifying correspondence to a regular expression;
    • expect().toContain() - verifying content in the array;
    • expect().toThrow() - test exception call;
    • expect().toHaveBeenCalled() - check function call.

    Additional functions

    BeforeEach/afterEach functions are implemented to avoid copying any logic used in the tests. They run accordingly before/after each test.

    Runs and waitsFor functions are used for testing asynchronous calls.

    • runs - takes an asynchronous function to implement;
    • waitsFor - takes three parameters: the first one is the function that should return true if the asynchronous call in runs function was executed, the second one is the error message, the third call is waiting in milliseconds.
    1. describe(“an example of asynchronous call ”, function () {
    2. var result = 0;
    3. function asyncFunc() {
    4. setTimeout(function() { result = result + 2; }, 500);
    5. }
    6. it(“test name”, function () {
    7. runs(function () {
    8. asyncFunc();
    9. });
    10. waitsFor(function() { return result === 2; }, “value didn’t change”, 2000);
    11. });
    12. });

    Watchers

    The ability to track  functions call is implemented by spyOn. This function takes two parameters: the first is the object for which the function is called, the second is the name of the function to be tracked.

    1. if(“verifying functions call”, function () {
    2. spyOn(exampleObject, 'exampleFunction');
    3. exampleObject.exampleFunction();
    4. expect(exampleObject.exampleFunction).toHaveBeenCalled();
    5. });

    During testing by spyOn, the number of calls can be tracked, their parameters and each call individually.
    To create a function without implementation, createSpy can be used. CreateSpy function takes the function name for identification.

    1. if(“verifying functions call”, function () {
    2. var example = createSpy('EXAMPLE');
    3. example(“param1”, “param2”);
    4. expect(example.identify).toHaveBeenCalledWith(“param1”, “param2”);
    5. expect(example.calls.length).toEqual(1);
    6. });

    Creating a mock object is done using createSpyObj. As parameters createSpyObj takes an object name and an array of strings that is a list of mock object methods.

    An example of test in Jasmine

    Alternatives

    Mocha

    https://mochajs.org/ - official website

    Mocha is a framework for testing JavaScript code, running on the basis of node.js. It supports work with browsers and asynchronous testing. It provides information about the degree of tests covering.

    Chai

    http://chaijs.com/ - official website

    Chai is a BDD/TDD assertions library for NodeJS and browser that can be easily implemented in conjunction with any JavaScript testing framework.

    QUnit

    http://qunitjs.com/ - official website

    QUnit is a library of JQuery developers, which allows writing unit tests for JavaScript code. It is the official tool for testing jQuery.

    ZombieJS

    http://zombie.js.org/ - official website

    ZombieJS is a lightweight framework for testing JavaScript code. It simulates a browser behavior.

    SinonJS

    http://sinonjs.org/ - official website

    SinonJS is a mock library for JavaScript, which can be used in any test framework.

    JSDoc

    Introduction

    Documentation is the necessary stage in creating a quality product.

    Documenting code is the process of describing functions, classes, methods using certain comments in the code, which makes the work with it easier in future, both for the author and other programmers.

    A well-documented project helps new developers understand the project better and quickly and amplifies control over its individual parts.

    One of the JavaScript code documentation tools is JSDoc.

    JSDoc is a documentation generator from source code comments in JavaScript. The syntax of JSDoc is similar to Javadoc, which is used for Java code documentation. Generated documentation is in HTML format.

    Official website

    http://usejsdoc.org/

    Implementation

    The documentation is generated from the source code comments.

    Comments start with a slash of two asterisks (/**) and end with a slash asterisk (*/). Each new line in the comment starts with an asterisk (*).

    The text of the documentation description is placed in this construction.

    Inside the comment tags can be used. Each tag begins with @.

    Tags

    • @author - Developer’s name;
    • @constructor - Indicates that the function is used as a constructor;
    • @deprecated - Indicates an out-of-date or not recommended function;
    • @description - Specifies function description;
    • @exception - Describes the exception;
    • @param - Describes the function parameter ( type is specified in curly brackets );
    • @private - Indicates the private method;
    • @property -Specifies information about the property in the object;
    • @return - Describes a return value;
    • @see - Describes connection with another object;
    • @summary - Specifies description for a function, like@description;
    • @this - Specifies a type of the object pointed to by this within the function;
    • @throw - Describes exception (type is specified in curly brackets);
    • @type - Specifies a type of variable (type is specified in curly brackets);
    • @typedef - Specifies a custom type (type is specified in curly brackets);
    • @version - Specifies a version of library.

    An example

    1. /**
    2. * @description Two numbers summing function.
    3. * @param {number} a - The first number.
    4. * @param {number} b - The second number.
    5. * @return {number}
    6. */
    7. function sum(a, b) {
    8. return a + b;
    9. }

    Generation of documentation

    Generation of documentation can be done using GulpJS. Plugin gulp-jsdoc is used for this. The plugin installation is:

    1. pm install gulp-jsdoc --save-dev

    The next step is to plug in the plugin in gulpfile.js:

    1. var jsdoc = require('gulp-jsdoc');

    The task to generate the documentation is created:

    1. gulp.task('jsdoc', function () {
    2. gulp.src('source-files')
    3. .pipe(jsdoc());
    4. });

    Alternatives

    YUIDoc

    http://yui.github.io/yuidoc/ - official website

    YUIDoc is a NodeJS application that is used to generate documentation from comments with syntax similar to Javadoc and Doxygen. This tool provides:

    • "Live preview".
    • Support of different programming languages.

    Docco

    http://jashkenas.github.io/docco/ - official website

    Docco is a documentation generator written in CoffeeScript Literate. Documentation Docco is a html page, where both source code and description text are represented.

    KarmaJS

    Introduction

    There are a lot of different tools that simplify the project development. A utility like KarmaJS is used to simplify the testing process of the project.

    KarmaJS is a console tool that allows running tests in different browsers, tracking changes in the source code by running tests automatically and allows determining the coverage percentage.

    Official website

    https://karma-runner.github.io/1.0/index.html 

    Features

    • Running tests from the console.
    • An automatic tests start after each change of the source code.
    • A support of various frameworks for testing (jasmine, mocha, qunit, etc.).
    • An ability of testing in several browsers.An ability to integrate with Jenkins.
    • Displaying degree of tests coverage.

    Start of work

    Several dependencies should be installed to get started with KarmaJS.

    Installation is performed using the npm package manager.

    It is also necessary for working with KarmaJS.

    Step 1: First you need to install KarmaJS:

    1. pm install -g karma-cli

    Step 2: Next, the emulator should be installed to test JavaScript code:

    1. pm install -g phantomjs

    Step 3: Then the necessary plug-ins should be installed to run tests in the required browsers. There are the following plug-ins for automatically opening browsers when running tests:

    • karma-chrome-launcher - Chrome;
    • karma-firefox-launcher - Mozilla Firefox;
    • karma-safari-launcher - Safari.

    Implementation

    Step 1: A configuration file should be firstly created to organize the tests  launch in KarmaJS. The following command is run to perform this:

    1. karma init

    This command will ask you to fill in some information about KarmaJS configuration, including information about the browsers where testing will be performed, tests location and other.

    Step 2: Next the configuration file should be configured.

    Parameters

    • files() - list of files to download;
    • exclude() - list of file exceptions from files();
    • reporters() - list of plug-ins used for displaying test results;
    • port() - the port of the web server;
    • runnerPort() - client’s port;
    • colors()  - enable / disable colors when logging to the console;
    • logLevel() - logging format;
    • autoWatch() - enable / disable automatic start of tests when source code changes;
    • browsers() - the list of browsers in which tests will be run (Chrome, Firefox, Safari, PhantomJS);
    • captureTimeout() - setting the timeout in milliseconds;singleRun()- for one-time start;
    • preprocessors()  - list of handlers applied to files, before downloading to the browser.

    Tests coverage degree

    To add displaying of the degree of tests coverage in KarmaJS the following steps should be done:

    Step 1: To add a mask of files in parameter preprocessors, the degree of which should be checked:

    1. preprocessors: {     'js/*.js': ['coverage']   }

    Step 2: To add the 'coverage'. line to the reporters parameter.
    Step 3: To add the parameters of the degree of  tests coverage:

    1. coverageReporter: {          type: 'text'        }

    Code quality checking

    To verify the quality of the code in KarmaJS it is necessary:

    Step 1: To set Jshint dependency:

    1. pm install jshint --save-dev

    Step 2:  To add a mask of files which code quality should be checked into preprocessors  parameter:

    1. preprocessors: {     'js/*.js': ['jshint']   }

    Example file karma.conf.js

    Tests run

    1. karma start