• Search form is empty!

  • Gulp Tutorial - Table of Contents

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face
    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - TOC/Index

    Table of Contents

    Quick reference to the Gulp tutorial series.

    Gulp Tutorial - Introduction
    Gulp Tutorial - Part 1 Reasons for build tools like Gulp
    Gulp Tutorial - Part 2 Setup
    Gulp Tutorial - Part 3 Adding Plugins
    Gulp Tutorial - Part 4 Sequence and Parallel Task Processing
    Gulp Tutorial - Part 5 Handling Errors with Plumber
    Gulp Tutorial - Part 6 Optimizing Javascript/Typescript
    Gulp Tutorial - Part 7 Optimizing CSS
    Gulp Tutorial - Part 8 Optimizing HTML
    Gulp Tutorial - Part 9 Image Optimization
    Gulp Tutorial - Part 10 JSON & Calling Grunt From Gulp
    Gulp Tutorial - Part 11 JSHINT
    Gulp Tutorial - Part 12 Typescript
    Gulp Tutorial - Part 13 SASS
    Gulp Tutorial - Part 14 Watch
    Gulp Tutorial - Part 15 Transforming Environment Variables
    Gulp Tutorial - Part 16 Useful Gulp Commands & Tips
    Gulp Tutorial - Part 17 GLOB Tips
    Gulp Tutorial - Part 18 Useful NPM Tips

    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face
    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 18 Useful NPM Tips

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 18

    Useful NPM Tips

    COMMANDS CHEAT SHEET

    Find outdated modules

    npm outdated -–depth=0
    npm outdated –-json -–depth=0


    Installing a package

    npm install grunt-contrib-uglify@* --save-dev

    Updating local packages

    When someone has added modules since your last check-in just run.
    npm update

    POWERSHELL (PRIMER)

    Windows users can use either the Command Prompt or PowerShell.

    PowerShell is pre-installed on Windows 8 or newer installations.

    From Start: Search programs and files type “powershell”. Select “powershell.exe”.

    enter image description here


    SYNTAX

    Powershell Command Syntax:

    application action –flags arguments
    


    For help with any application add the –h or –help flags for additional instructions.

    The tab key autocompletes your statement.

    ADDING AND REMOVING FILES

    To create a new item use the ni command. This might not seem useful with Visual Studio 2013 because any file added must also be added to your project file. Visual Studio 2015 does not have a project file needing updates. Instead a Glob pattern is used to determine what files should and should not be included in the project. That being the case, suddenly, ni makes more sense.

    Adding files

    ni newjsfile.js -type file
    new-item newjsfile.js –type file


    Removing files

    ri newjsfile.js or remove-item newjsfile.js


    INSTALLING NODEJS AND NPM PACKAGES

    Install NodeJS from:
    https://nodejs.org/

    Install NPM packages with the following syntax
    npm install [global option –g] [package-name] [options]

    Example: (You need to install Gulp both locally and globally)

    npm install gulp --save-dev
    npm install gulp –g


    https://docs.npmjs.com/getting-started/installing-npm-packages-locally

    NPM VERSION UPDATES

    There are multiple options for keeping NPM packages up to date. The approach you choose might depend on your development workflow and automated testing solution, i.e., if you have good automated testing, it might be safe to allow the latest versions. If not, you might want to choose a more deliberate approach to NPM versioning.

    VERSION UPDATES: OPTION 1 – USING NODE TOOLS

    Check to see which NPM packages are out of date

    Display colored rows
    npm outdated -–depth=0

    Display in json which includes current, wanted, latest version numbers
    npm outdated –-json -–depth=0

    enter image description here


    Note: Not all your packages will be displayed. Only the outdated packages will be displayed.

    Note: If you modify the command to include “-g” then you’ll get a list of your outdated global packages.

    To update packages one at a time

    npm install [package-name]@* [save?]
    npm install grunt-contrib-uglify@* --save-dev


    VERSION UPDATES: OPTION 2 – USING NPM-CHECK-UPDATES

    Using the npm-check-updates package, you can keep all your packages updated.
    https://www.npmjs.com/package/npm-check-updates
    npm install -g npm-check-updates

    Then execute the following command to see what packages can be updated.
    npm-check-updates

    enter image description here


    To upgrade all your packages

    npm-check-updates –u [-g option for global packages]

    Now your package.json is updated.

    Then execute an NPM install to update the package installations.

    npm install [-g option for global packages]

    NPM VERSIONING SEMANTICS

    https://docs.npmjs.com/misc/semver
    http://semver.org/


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 17 GLOB Tips

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 17

    GLOB Tips

    Here are some of the more common Glob patterns.

    “dir/*” – includes all files

    “dir/**” – includes all files and folders

    “**/*.js” – all JavaScript files

    “!**/*.min.js” – excludes all minified JavaScript files

    “!app/lib/**/*” – excludes all files in the lib folder.

    https://github.com/isaacs/node-glob
    http://mywiki.wooledge.org/glob#preview


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 16 Useful Gulp Commands & Tips

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 16

    Useful Gulp Commands & Tips

    Installing Gulp

    Execute both of these. The first adds Gulp locally so it can be used by NPM. The second installs Gulp globally so it can be accessed from the command line.

    npm install gulp --save-dev
    npm install gulp -g


    Retrieve Gulp version

    Grunt -version

    Installing plugins

    The syntax for Grunt plugins is
    install [plugin-name] --save-dev

    For example, if you want to minify and concatenate your JavaScript for performance, you would install two plugins.

    Perform a quick Google search and you’ll find this site
    https://github.com/gruntjs/grunt-contrib-uglify
    npm install grunt-contrib-uglify --save-dev

    Perform a quick google search and you’ll find this site
    https://github.com/gruntjs/grunt-contrib-concat
    npm install grunt-contrib-concat --save-dev

    Retrieve Gulp version

    Gulp --v

    Every Gulp file needs a default task. To execute Gulp’s default task

    grunt

    It’s useful to run specific tasks that you have configured

    grunt [task-name]

    Get a list of Grunt commands

    Grunt –help

    To verify a plugin is not blacklisted

    Gulp --verify

    Testing tasks while building your gulpfile.js
    You can type gulp [task-name] and your task will run. If it has any dependencies then those dependencies will run first.

    gulp [task-name]


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 15 Transforming Environment Variables

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 15

    Transforming Environment Variables

    Most applications are expected to function in multiple environments. When coding you expect the application to function in the local environment. When you deploy to the test environment you expect it to function there and the same for production.

    We will use Gulp to set an Angular constant used to build the connection URI to each WebApi.

    Create a json file representing each possible environment in the “src” folder.

    env.config.localdev.json

    Create this file with the following content.

    { 
        "myFirstApi":  "http://localhost:52335",
        "mySecondApi":  "http://localhost:52336"
    }


    env.config.dev.json

    Create this file with the following content.

    { 
        "myFirstApi":  "http://devFirstApi",
        "mySecondApi":  "http://devSecondApi"
    }


    env.config.stage.json

    Create this file with the following content.

    { 
        "myFirstApi":  "http://stageFirstApi",
        "mySecondApi":  "http://stageSecondApi"
    }


    env.config.prod.json

    Create this file with the following content.

    { 
        "myFirstApi":  "http://prodFirstApi",
        "mySecondApi":  "http://prodSecondApi"
    }


    Each file contains the connection string for each WebApi used.

    Create an Angular constant in the app.js file

    // ---------------------------------------------------------------------------------------------
    // Application Constants
    // ---------------------------------------------------------------------------------------------
    mashupApp.constant('apiUrl', { 'myFirstApi': '@@myFirstApi' },
                                 { 'mySecondApi': '@@mySecondApi' });


    From the command-line install

    npm install gulp-replace-task --save-dev
    npm install yargs --save-dev
    npm install fs --save-dev


    Add the module to the Gulp file

        , replace               = require('gulp-replace-task')
        , args                  = require('yargs').argv
        , fs                    = require('fs')


    Add the task to the Gulp file

    This will be different for your environment. You might have a different path to your configuration files and WebApi names.

    gulp.task(' setEnv', function () {
        // Get the environment from the command line
        var env = args.env || 'localdev';
    
        // Read the settings from the right file
        var filename = 'env.config.' + env + '.json';
        var settings = JSON.parse(fs.readFileSync('dist/' + filename, 'utf8'));
    
        // Replace each placeholder with the correct value for the variable.  
        gulp.src('src/app.js')
          .pipe(replace({
              patterns: [
                {
                    match: 'myFirstApi',
                    replacement: settings. myFirstApi
                },
                {
                    match: 'mySecondApi',
                    replacement: settings. mySecondApi
                },
              ]
          }))
          .pipe(gulp.dest('dist/./'));
    });


    Add the new task to the default task

    gulp.task('default', function () {
        runSequence('annotate', 'clean-dist', 'copy',
                    ['coreservices', 'routeconfig', 'libs', 'minifyhtml', 'minifyimage'
                        , 'grunt-merge-json:menu', 'jshint', 'tscompile', 'tslint', 'sass'
                        , 'setEnv']
                    , ['uglifyalljs', 'minifycss']
                    , 'watch');
    });


    You can execute the task individually
    The first option uses the prod configuration. The second uses the default which happens to be the localdev configuration.

    To change the environment manually execute the one of the following commands. The first executes the setEnv task and passes in the –env parameter with the value of prod. The env.config.prod.json file will be used.

    Gulp setEnv --env prod
    Or
    Gulp setEnv

    Before the app.js is changed by the setEnv task.

    // ---------------------------------------------------------------------------------------------
    // Application Constants
    // ---------------------------------------------------------------------------------------------
    mashupApp.constant('apiUrl', { 'myFirstApi': '@@myFirstApi' },
                                 { 'mySecondApi': '@@mySecondApi' });
    
     
    Before the app.js is changed by the setEnv task.
    // ---------------------------------------------------------------------------------------------
    // Application Constants
    // ---------------------------------------------------------------------------------------------
    mashupApp.constant('apiUrl', { 'myFirstApi': 'http://localhost:52335' },
                                 { 'mySecondApi': 'http://localhost:52336' });


    Add to the default task

    I’ve added the setEnv to the early part of the default configure so it executes before the minification task is run.

    gulp.task('default', function () {
        runSequence('annotate', 'clean-dist', 'copy',
                    ['coreservices', 'routeconfig', 'libs', 'minifyhtml', 'minifyimage'
                        , 'grunt-merge-json:menu', 'jshint', 'tscompile', 'tslint', 'sass'
                        , 'setEnv']
                    , ['uglifyalljs', 'minifycss']
                    , 'watch');
    });


    Now I can simply type Gulp and all my tasks, including the Replace task will run.

    gulp

    If you want to create a fresh distribution folder for production you could type

    gulp --env prod

    When no –env parameter is provided the default parameter value is used as described in code. In this case the default value is “localdev”.


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 14 Watch

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 14

    Watch

    Running the default task for Gulp, with all our tasks included, will consume more CPU and time than is required during development where files are changed one at a time. For dealing with individual files as they change, we can use the Watch plugin.

    When the Watch is triggered, gulp.watch tasks execute.

    From the command-line install

    npm install gulp-watch --save-dev

    Add the module to the Gulp file

    , watch = require('gulp-watch')

    Add the task to the Gulp file

    The “watch” task is large and uses many other tasks, so I place it at the bottom of the file so it is separate.

    gulp.task('watch', function () {
    
        // ---------------------------------------------------------------
        // Watching JS files
        // ---------------------------------------------------------------
        // Copy all files except *.js files.
        gulp.watch(['src/**/*', '!src/**/*.js', '!bower_components/**.*'], function () { runSequence('copy'); });
    
        // Annotates and copies *.js files
        gulp.watch(['src/**/*.js',
            '!src/core/config/route.config.js', '!src/apps/**/route.config.js',
            '!bower_components/**/*.js'], function () { runSequence('watch:annotate', 'copy'); });
    
        // routeConfig file changes.
        gulp.watch(['src/core/config/route.config.js', 'src/apps/**/route.config.js'], function () { runSequence('routeconfig'); });
    
        // Uglify JS files
        gulp.watch(['dist/**/*.js', '!dist/**/*.min.js', '!dist/core/lib/**/*', '!dist/core/common/**/*'], function () { runSequence('uglifyalljs'); });
    
    
        // ---------------------------------------------------------------
        // Watching Bower components
        // ---------------------------------------------------------------        
        gulp.watch(['bower_components/**/*.js'], function () { runSequence('libs'); });
        // TODO: Add other bower component types like css, scss and images
    
    
        // ---------------------------------------------------------------
        // Watching css and scss files
        // ---------------------------------------------------------------
        gulp.watch(['dist/**/*.css', '!dist/**/*.min.css', '!dist/core/lib/**/*'], function () { runSequence('minifycss'); });
        gulp.watch(['dist/**/*.scss', '!dist/core/lib/**/*'], function () { runSequence('sass'); });
    
        // ---------------------------------------------------------------
        // Watching TypeScript files
        // ---------------------------------------------------------------
        gulp.watch(['dist/**/*.ts', '!dist/core/lib/**/*.*', '!dist/core/css/**/*.*'], function () { runSequence('tscompile'); });
    
        // ---------------------------------------------------------------
        // Watch - Execute linters
        // ---------------------------------------------------------------
        gulp.watch(['dist/**/*.ts', '!dist/core/lib/**/*.*', '!dist/core/css/**/*.*'], function () { runSequence('tslint'); });
        //gulp.watch(['dist/**/*.js', '!dist/core/lib/**/*.*', '!dist/**/*.min.js', '!dist/core/css/**/*.*'], function() { runSequence('jshint'); });
    
    
        gulp.watch(['dist/**/*.js', '!dist/core/lib/**/*.*', '!dist/**/*.min.js', '!dist/core/css/**/*.*'], ['jshint']);
    
        // ---------------------------------------------------------------
        // Watching image files
        // ---------------------------------------------------------------
        // unable to get this watch to ever notice a file changed.  This will be handled on the initial build.
        //gulp.watch(['dist/**/*.{png,jpg,gif,ico}', '!dist/core/lib/**/*.*', '!dist/core/css/**/*.*'], function() { runSequence('minifyimage'); });
    
    });


    Add another task to the gulp file

    Also add this supporting Watch task. This helps improve performance with the “newer” plugin.

    // ---------------------------------------------------------------
    // Watch specific tasks.  This is to support the use of newer.
    // ---------------------------------------------------------------
    gulp.task('watch:annotate', function () {
        return gulp.src(['src/index.controller.js', 'src/core/**/*.js', 'src/apps/**/*.js', '!src/core/lib/**/*', '!/**/*.min.js'], { base: 'src/./' })
          .pipe(plumber({
              errorHandler: onError
          }))
          .pipe(newer('src/./'))
          .pipe(ngAnnotate())
          .pipe(gulp.dest('src/./'));
    });


    Add the new task to the default task

    Add the new “watch” task to the default task. The default task will execute all the tasks in the sequence specified by the runSequence function. The last task run is the Watch task which contains 10 individual Watch tasks. This time, when you run the Gulp default task, the command line will not return control to you. To break out of this, press CTRL + C and then answer the prompt with “y”.

    gulp.task('default', function () {
        runSequence('annotate', 'clean-dist', 'copy',
                    ['coreservices', 'routeconfig', 'libs', 'minifyhtml', 'minifyimage'
                        , 'grunt-merge-json:menu', 'jshint', 'tscompile', 'tslint', 'sass']
                    , ['uglifyalljs', 'minifycss']
                    ,'watch');
    });


    Run the default task

    gulp


    enter image description here

    If you modify any files the Watch is configured to watch, then you’ll see tasks run.

    Here is what happens after changing the index.controller.js file.

    enter image description here

    First the annotate task runs against the changed JavaScript code. Then the file is copied to the dist folder and minified by the uglifyalljs task. Finally the JavaScript code is linted with the jshint task.


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 13 SASS

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 13

    SASS

    For your SASS implementation, we will use the Gulp-SASS plugin.

    From the command-line install

    npm install gulp-sass --save-dev

    Add the module to the Gulp file

    , sass = require('gulp-sass')

    Add the task to the Gulp file

    gulp.task('sass', function () {
        gulp.src('./dist/**/*.scss', { base: 'dist/./' })
          .pipe(plumber({
              errorHandler: onError
          }))
            .pipe(sass())
            .pipe(gulp.dest('dist/./'));
    });


    Add the new task to the default task

    gulp.task('default', function () {
        runSequence('annotate', 'clean-dist', 'copy',
                    ['coreservices', 'routeconfig', 'libs', 'minifyhtml', 'minifyimage'
                        , 'grunt-merge-json:menu', 'jshint', 'tscompile', 'tslint', 'sass'],
                    ['uglifyalljs', 'minifycss']);
    });


    Run the default task

    gulp


    Learn more about SASS here

    http://sass-lang.com/


    enter image description here


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 12 Typescript

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 12

    Typescript

    TypeScript is a language used to build large-scale JavaScript applications. TypeScript code is transpiled down to ES5 JavaScript. Angular 2.0 is written in TypeScript and ES2015/ES2016, formerly ES6/ES7, features are available in TypeScript.

    Links for installing TypeScript, for your version of Visual Studio, are here
    http://www.typescriptlang.org/

    Dan Wahlin’s take on TypeScript in a Gulp workflow
    http://weblogs.asp.net/dwahlin/creating-a-typescript-workflow-with-gulp

    The TypeScript file for this tutorial

    The MashupJS isn’t using TypeScript yet so I created a TypeScript file for this example.

    I created a file in the root of the scr folder named myTypeScript.ts.

    I added the following code snippet from http://www.typescriptlang.org/Playground to the new file.

    class Greeter {
        greeting: string;
        constructor(message: string) {
            this.greeting = message;
        }
        greet() {
            return "Hello, " + this.greeting;
        }
    }
    
    var greeter = new Greeter("world");
    
    var button = document.createElement('button');
    button.textContent = "Say Hello";
    button.onclick = function() {
        alert(greeter.greet());
    }


    document.body.appendChild(button);

    Expected result

    Once we’ve transpiled the TypeScript down to JavaScript (ES5) we will get a myTypeScript.js file and a minified version. Here is what the JS file should look like.

    var Greeter = (function () {
        function Greeter(message) {
            this.greeting = message;
        }
        Greeter.prototype.greet = function () {
            return "Hello, " + this.greeting;
        };
        return Greeter;
    })();
    var greeter = new Greeter("world");
    var button = document.createElement('button');
    button.textContent = "Say Hello";
    button.onclick = function () {
        alert(greeter.greet());
    };
    document.body.appendChild(button);


    Installing plugins

    npm install gulp-typescript --save-dev
    npm install gulp-tslint --save-dev
    npm install gulp-tslint-stylish --save-dev


    Add the new plugins to your Gulp required list

    , ts                    = require('gulp-typescript')
    , tslint                = require('gulp-tslint')
    , tsstylish             = require('gulp-tslint-stylish')


    Add the new task to your gulpfile.js

    gulp.task('tscompile', function () {
        return gulp.src(['./dist/**/*.ts', '!dist/core/lib/**/*.*', '!dist/core/css/**/*.*'])
          .pipe(plumber({
              errorHandler: onError
          }))
        .pipe(sourcemaps.init())
        .pipe(ts({
            target: 'ES5',
            declarationFiles: false,
            noExternalResolve: true
        }))
        .pipe(rename({ extname: '.js' }))
        .pipe(gulp.dest('dist/./'));
    });


    And add the new task to your default task

    gulp.task('default', function () {
        runSequence('annotate', 'clean-dist', 'copy',
                    ['coreservices', 'routeconfig', 'libs', 'minifyhtml', 'minifyimage'
                        , 'grunt-merge-json:menu', 'jshint', 'tscompile'],
                    ['uglifyalljs', 'minifycss']);
    });


    Executing the task

    You can execute the task individually
    gulp


    enter image description here

    How it works

    First the task transpiles the TypeScript code down to ES5, ECMAScript 5.

    Then the new ES5 JavaScript is emitted. This file will not be used by the min.js.map. The map file will point directly to the TypeScript, “.ts”, file. The reason we are emitting the “.js” is so the TypeScript code can participate in the JSHint process. You’ll notice the ‘jshint’ task now has a dependency on the ‘tscompile’ task via the runSequence function.

    Finally the TypeScript file is emitted as a minified JavaScript file with an associated map file linking it back to the TypeScript file.

    jshint-output.html

    If you run the new task with gulp tscompile, you’ll notice the jshint-output.html file has been updated.

    If you double-click this file from explorer.exe, then you’ll notice our JavaScript, emitted by TypeScript, has a few issues.

    enter image description here

    Fixing the JSHint warnings

    These are pretty simple changes to make. Replace all the double quotes with single quotes and define the alert() method and JSHint is satisfied. The end result should be this.

    /*global alert */

    class Greeter {
        greeting: string;
        constructor(message: string) {
            this.greeting = message;
        }
        greet() {
            return 'Hello, ' + this.greeting;
        }
    }
    
    var greeter = new Greeter('world');
    
    var button = document.createElement('button');
    button.textContent = 'Say Hello';
    button.onclick = function () {
        alert(greeter.greet());
    }
    
    document.body.appendChild(button);


    Linting TypeScript

    TypeScript has language constructs ES5 JavaScript does next so automating a TypeScript specific linter might seem redundant. It’s not.

    Add the following task to your gulpfile.js

    gulp.task('tslint', ['copy'], function () {
        return gulp.src(['./dist/**/*.ts', '!dist/core/lib/**/*.*', '!dist/core/css/**/*.*'])
            .pipe(tslint())
            .pipe(tslint.report('verbose', {
                emitError: false,
                sort: true,
                bell: true
            }))
    });


    TSLint reporter

    I was unable to find a plugin to export TSLint errors to an HTML file as we did for JSHint. If this plugin becomes available, I’ll add it to this post.

    TSLint configuration

    Configuration information for TSLint is stored in a file named tslint.json.

    Here is a good starting point. I’ve borrowed this from other developer posts and it seems to be a good list.

    Create a tslint.json file in the same folder as your gulpfile.js and package.json and add the following code to it.

    {
        "rules": {
            "class-name": true,
            "curly": true,
            "eofline": false,
            "forin": true,
            "indent": [true, 4],
            "label-position": true,
            "label-undefined": true,
            "max-line-length": [true, 140],
            "no-arg": true,
            "no-bitwise": true,
            "no-console": [true,
              "debug",
              "info",
              "time",
              "timeEnd",
              "trace"
            ],
            "no-construct": true,
            "no-debugger": true,
            "no-duplicate-key": true,
            "no-duplicate-variable": true,
            "no-empty": true,
            "no-eval": true,
            "no-imports": true,
            "no-string-literal": false,
            "no-trailing-comma": true,
            "no-trailing-whitespace": true,
            "no-unused-variable": false,
            "no-unreachable": true,
            "no-use-before-declare": true,
            "one-line": [true,
              "check-open-brace",
              "check-catch",
              "check-else",
              "check-whitespace"
            ],
            "quotemark": [true, "single"],
            "radix": true,
            "semicolon": true,
            "triple-equals": [true, "allow-null-check"],
            "variable-name": false,
            "whitespace": [true,
              "check-branch",
              "check-decl",
              "check-operator",
              "check-separator"
            ]
        }
    }


    Run the default task

    gulp


    enter image description here

    For more information

    https://www.npmjs.com/package/gulp-typescript


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 11 JSHINT

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 11

    JSHINT

    JSHint is a static analysis tool used to analyze JavaScript code for quality and standards/style enforcement. The example below demonstrates how to analyze your code but it can also be piped into transpilation of code from TypeScript to JavaScript.

    Install the gulp-jshint, jshint-stylish, and gulp-jshint-html-reporter.

    npm install gulp-jshint --save-dev
    npm install jshint-stylish --save-dev
    npm install gulp-jshint-html-reporter --save-dev


    Add the new plugins to your Gulp required list

    , jshint                = require('gulp-jshint')
    , stylish               = require('jshint-stylish')
    , jshintfileoutput      = require('gulp-jshint-html-reporter')


    Add the new task to your gulpfile.js

    gulp.task('jshint', function () {
        //gulp.task('jshint', ['copy', 'tscompile'], function () {
        return gulp.src(['./dist/**/*.js', '!dist/core/lib/**/*.*', '!**/*.min.js', '!dist/core/css/**/*.*'])
          .pipe(plumber({
              errorHandler: onError
          }))
          .pipe(jshint('.jshintrc'))
          .pipe(jshint.reporter(stylish))
          .pipe(jshint.reporter('gulp-jshint-html-reporter', { filename: 'jshint-output.html' }))
        ;
    });


    Creating a .jshintrc file

    You can customize your own jshint rules in a file called .jshintrc. I’m starting with options recommended by John Papa.
    https://github.com/johnpapa/angular-styleguide#use-an-options-file


    .jshintrc TIP

    You cannot easily create files beginning with a dot in Windows.

    Steps to create the .jshintrc file:

    • Create a file named “.jshintrc.” in the root alongside gulpfile.js and Gruntfile.js. Notice the ending dot. You must do this from Explorer.
    • Windows will prompt you to confirm the extension.
    • Finally Windows simply removes the ending dot for you. Now you have the file “.jshintrc”.
    • If you are using Visual Studio .NET or some other IDE, you can now go and add the existing file to your project.

    .jshintrc content

    We are going to use the options promoted by John Papa.

    Copy and paste this into your new .jshintrc file or visit John Papa’s page with the link above to see if any new updates have become available.

    {
        "bitwise": true,
        "camelcase": true,
        "curly": true,
        "eqeqeq": true,
        "es3": false,
        "forin": true,
        "freeze": true,
        "immed": true,
        "indent": 4,
        "latedef": "nofunc",
        "newcap": true,
        "noarg": true,
        "noempty": true,
        "nonbsp": true,
        "nonew": true,
        "plusplus": false,
        "quotmark": "single",
        "undef": true,
        "unused": false,
        "strict": false,
        "maxparams": 10,
        "maxdepth": 5,
        "maxstatements": 40,
        "maxcomplexity": 8,
        "maxlen": 120,
    
        "asi": false,
        "boss": false,
        "debug": false,
        "eqnull": true,
        "esnext": false,
        "evil": false,
        "expr": false,
        "funcscope": false,
        "globalstrict": false,
        "iterator": false,
        "lastsemic": false,
        "laxbreak": false,
        "laxcomma": false,
        "loopfunc": true,
        "maxerr": false,
        "moz": false,
        "multistr": false,
        "notypeof": false,
        "proto": false,
        "scripturl": false,
        "shadow": false,
        "sub": true,
        "supernew": false,
        "validthis": false,
        "noyield": false,
    
        "browser": true,
        "node": true,
    
        "globals": {
            "angular": false,
            "$": false
        }
    }


    Using JSHint reporters

    Reporters receive feedback from JSHint and format it into something human readable. By default, you’ll get raw text from JSHint and it will be displayed at the command line. Adding the jshint-stylish plugin and passing it to the jshint.reporter(stylish) gives you a more readable output to the command line.


    enter image description here


    Taking this concept a step further, the gulp-jshint-html-reporter generates an html document, as the name of the plugin implies.

    For more information

    https://www.npmjs.com/package/gulp-jshint-html-reporter
    https://github.com/ivan-vesely/gulp-jshint-html-reporter

    There isn’t much in the way of documentation but the source code is available and you have access to the author here.

    enter image description here

    Options list

    http://jshint.com/docs/options/

    For more information

    https://www.npmjs.com/package/gulp-jshint

    Run the default task

    gulp


    enter image description here

    Tip

    The jshint-output.html file is a good indicator of how your recent changes might have deviated from your standard or best practices. By checking this file into source control you can see if the file changes. If it does not, then no new errors are being reported. If it does change, then either old errors have been corrected or new errors have been detected.


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 10 JSON & Calling Grunt From Gulp

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 10

    JSON & Calling Grunt From Gulp

    On occasion you might need to combine JSON files. The MashupJS allows each app in the apps folder to define its own menu items. At build time we need these JSON files to be combined and saved with a specific file name so the menu.html template has access to all the menu items.

    Edge case: Calling Grunt tasks from Gulp


    So as it turns out, some of our favorite plugins used in Grunt are not available in Gulp. Before using Gulp I used Grunt and a plugin named “grunt-merge-json” to combine separate JSON files. Not only did it combine the JSON but merged them and eliminated duplication. I tried several Gulp plugins but nothing worked as expected. In time, a developer will build this plugin for Gulp but until then we can execute Grunt commands from our Gulp implementation.

    From the command-line install

    npm install -g grunt-cli
    npm install grunt-merge-json --save-dev


    Create a Gruntfile

    Create a basic Gruntfile.js with the following content, in the root of your project.

    module.exports = function (grunt) {
    
        grunt.initConfig({
            distFolder: 'dist',
    
            pkg: grunt.file.readJSON('package.json'),
            "merge-json": {
    
                menu: {
                    src: ['src/apps/**/menu.json.txt'],
                    dest: '<%= distFolder %>/menu.json.txt',
                },
            },
        });
    
        // Load modules, register tasks
        grunt.loadNpmTasks('grunt-merge-json');
    };


    Install Gulp-Grunt from the command-line

    npm install gulp-grunt --save-dev

    For more information

    https://www.npmjs.com/package/gulp-grunt

    Add Grunt configuration to Gulp

    Place this Grunt configuration code in the gulpfile.js just as you would with any other task.

    // -------------------------------------------------
    // Grunt configuration
    require('gulp-grunt')(gulp, {
        // These are the default options but included here for readability.
        base: null,
        prefix: 'grunt-',
        verbose: false
    });
    // -------------------------------------------------


    These are default configurations. The base represents the path to the Gruntfile.js. Because the Gruntfile.js is in the root folder base: can be null.

    We can now call the Grunt task the same way we would a Gulp task but with the prefix “grunt=”.

    Test Grunt Plugin

    Gulp grunt-merge-json:menu

    Add the new Grunt task to the default task.

    gulp.task('default', function () {
        runSequence('annotate', 'clean-dist', 'copy',
                    ['coreservices', 'routeconfig', 'libs', 'minifyhtml', 'minifyimage'
                        , 'grunt-merge-json:menu'],
                    ['uglifyalljs', 'minifycss']);
    });


    Run the default task

    gulp


    enter image description here


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 9 Image Optimization

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 9

    Image Optimization

    Install the gulp-imagemin and imagemin-pngquant plugins. The gulp-imagemin comes with several optimizers for different image types, but does very little for PNG files. The imagemin-pngquant will focus on optimizing PNG files.

    I’ve decided to leave the third party libraries alone, but you might choose to optimize them as well. This demo is focused on optimizing our own images.


    From the command-line install

    npm install gulp-imagemin --save-dev
    npm install imagemin-pngquant --save-dev


    Add the modules to the Gulp file

    , imagemin              = require('gulp-imagemin')
    , pngquant              = require('imagemin-pngquant')


    Add the task to the Gulp file

    gulp.task('minifyimage', function () {
        return gulp.src(['dist/**/*.{png,jpg,gif,ico}', '!dist/core/lib/**/*.*', '!dist/core/css/**/*.*'])
          .pipe(plumber({
              errorHandler: onError
          }))
        .pipe(imagemin({ progressive: true, optimizationLevel: 7, use: [pngquant()] }))
        .pipe(gulp.dest('dist/./'));
    });


    Add the new task to the default task

    gulp.task('default', function () {
        runSequence('annotate', 'clean-dist', 'copy',
                    ['coreservices', 'routeconfig', 'libs', 'minifyhtml', 'minifyimage'],
                    ['uglifyalljs', 'minifycss']);
    });

    Run the default task

    gulp


    enter image description here


    For more information

    https://www.npmjs.com/package/gulp-imagemin
    https://www.npmjs.com/package/imagemin-pngquant


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 8 Optimizing HTML

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 8

    Optimizing HTML


    HTML presents another opportunity for optimization. With every “bit” we can squeeze out of the code, the healthier is the application. HTML optimization is more noticeable as the HTML file becomes larger.

    From the command-line install

    npm install gulp-minify-html --save-dev

    Add the module to the Gulp file

    , minifyhtml = require('gulp-minify-html')

    Add the task to the Gulp file

    gulp.task('minifyhtml', function () {
        return gulp.src(['dist/**/*.html', '!/**/*.min.html', '!dist/core/lib/**/*'], { base: 'dist/./' })
          .pipe(plumber({
              errorHandler: onError
          }))
         .pipe(sourcemaps.init())
         .pipe(minifyhtml())
         .pipe(rename({
             extname: '.min.html'
         }))
         .pipe(sourcemaps.write('./'))
         .pipe(gulp.dest('dist/./'));
    });


    Small templates won’t realize much improvement with HTML minification, but every little bit helps. Larger HTML files will benefit, but while we’re at it, let’s just minify all HTML files.

    Add new task to the default task

    gulp.task('default', function () {
        runSequence('annotate', 'clean-dist', 'copy',
                    ['coreservices', 'routeconfig', 'libs', 'minifyhtml'],
                    ['uglifyalljs', 'minifycss']);
    });


    Run the default task

    gulp


    enter image description here


    For more information on gulp-minify-html.

    https://www.npmjs.com/package/gulp-minify-html


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 7 Optimizing CSS

    http://robertdunaway.github.io

    http://mashupjs.github.io

    The Mashup is a learning tool that serves as a seed project for line-of-business applications. It’s goal is a shortened learning curve for building modern business applications and the reduction of technical debt.

    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today

    Gulp Tutorial - Part 7

    Optimizing CSS

    CSS gives us another opportunity for optimization. SASS is a higher-level language for CSS that can be transpiled down to CSS similar to how TypeScript is transpiled down to JavaScript. Later in this tutorial, we will add a task for transpiling SASS to CSS.

    In this task, we will optimize all existing CSS files.

    From the command-line install

    npm install gulp-minify-css --save-dev

    Add the module to the Gulp file

    , minifycss = require('gulp-minify-css')

    Add the task to the Gulp file

    gulp.task('minifycss', ['copy'], function () {
        return gulp.src(['dist/**/*.css', '!/**/*.min.css', '!dist/core/lib/**/*'], { base: 'dist/./' })
         .pipe(sourcemaps.init())
         .pipe(minifycss())
         .pipe(rename({
             extname: '.min.css'
         }))
         .pipe(sourcemaps.write('./'))
         .pipe(gulp.dest('dist/./'));
    });


    Add the new task to the default task

    gulp.task('default', function () {
        runSequence('annotate', 'clean-dist', 'copy',
                    ['coreservices', 'routeconfig', 'libs'],
                    ['uglifyalljs', 'minifycss']);
    });


    Run the default task

    gulp


    enter image description here


    Rather than concatenating CSS files, we are simply minifying them in place and creating maps.

    Later, when transpiling from SASS, we won’t need concatenation because the “@import” statement will pull multiple source files together for us.

    For more information

    https://www.npmjs.com/package/gulp-minify-css


    Source code for this tutorial

    Start the tutorial using this code base:

    https://github.com/MashupJS/gulp-tutorial


    A completed tutorial can be found here:

    https://github.com/MashupJS/gulp-tutorial-end-result


    Smiley face

    This tutorial and more can be found in

    Gulp - Quick guide to getting up and running today