Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Alter The Ionic 2 Gulp Script To Include Browser JavaScript Files

TwitterFacebookRedditLinkedInHacker News

Recently I found myself needing to add a JavaScript library to an Ionic 2 TypeScript project. Now you’ll probably recall that I’ve written two different articles regarding using JavaScript libraries in TypeScript project. I wrote about including a JavaScript library in an Ionic 2 app in a guest post I did, but the scenario had the JavaScript library coming from the Node Package Manager (NPM). I also wrote about including a JavaScript library in an Angular app, but the project structure is a little more web friendly in that scenario.

My new scenario is including a JavaScript file, rather than NPM package. The project structure in an Ionic 2 application is a bit different than others. We can’t just include JavaScript files wherever we want because the build process could very well wipe them out. Instead we have to change the Gulp build process for the Ionic 2 application.

We’re going to see how to alter the Ionic 2 Gulp script to allow us to include external JavaScript files in our project.

I won’t be explaining a particular JavaScript library in this example, but more how to include them in your project with Gulp. For simplicity, let’s start by creating a fresh project. From the Command Prompt (Windows) or Terminal (Mac and Linux), execute the following:

ionic start GulpProject blank --v2 --typescript
cd GulpProject
ionic platform add ios
ionic platform add android

A few things to take note of in the above commands. First, notice the --v2 and --typescript tags. These say that we’re going to be creating an Ionic 2 TypeScript project. That said, you’ll need the Ionic 2 CLI, not Ionic Framework 1. The second thing to note is that if you’re not using a Mac with Xcode installed, you cannot build for the iOS platform.

When it comes to our Gulp process, we actually want to work with a single external JavaScript file. I don’t mean we can only use one external JavaScript file, I mean that we don’t want a mess of any number of files. This means we’ll have to concatenate, or merge the libraries together. This requires us to have the gulp-concat package installed.

From the Terminal or Command Prompt, execute the following:

npm install gulp-concat --save

What comes next will take place in the project’s gulpfile.js file and www/index.html file. Before we start writing code, create a www/extlibs directory and add some JavaScript files to it. These are the files that will be used in the project.

Open the project’s gulpfile.js file and include the following code. We’ll break it down after.

var gulp = require('gulp'),
    gulpWatch = require('gulp-watch'),
    del = require('del'),
    runSequence = require('run-sequence'),
    argv = process.argv;

gulp.task('serve:before', ['watch']);
gulp.task('emulate:before', ['build']);
gulp.task('deploy:before', ['build']);
gulp.task('build:before', ['build']);

var shouldWatch = argv.indexOf('-l') > -1 || argv.indexOf('--livereload') > -1;
gulp.task('run:before', [shouldWatch ? 'watch' : 'build']);

var buildBrowserify = require('ionic-gulp-browserify-typescript');
var buildSass = require('ionic-gulp-sass-build');
var copyHTML = require('ionic-gulp-html-copy');
var copyFonts = require('ionic-gulp-fonts-copy');
var copyScripts = require('ionic-gulp-scripts-copy');
var gulpConcat = require('gulp-concat');

var isRelease = argv.indexOf('--release') > -1;

gulp.task('watch', ['clean'], function(done){
    runSequence(
        ['sass', 'html', 'fonts', 'scripts', 'extlibs'],
        function(){
            gulpWatch('app/**/*.scss', function(){ gulp.start('sass'); });
            gulpWatch('app/**/*.html', function(){ gulp.start('html'); });
            buildBrowserify({ watch: true }).on('end', done);
        }
    );
});

gulp.task('build', ['clean'], function(done){
    runSequence(
        ['sass', 'html', 'fonts', 'scripts', 'extlibs'],
        function(){
            buildBrowserify({
            minify: isRelease,
            browserifyOptions: {
                debug: !isRelease
            },
            uglifyOptions: {
                mangle: false
            }
            }).on('end', done);
        }
    );
});

gulp.task('extlibs', function() {
    return gulp.src(['www/extlibs/*.js'])
        .pipe(gulpConcat('external-libraries.js'))
        .pipe(gulp.dest('www/build/js'));
});

gulp.task('sass', buildSass);
gulp.task('html', copyHTML);
gulp.task('fonts', copyFonts);
gulp.task('scripts', copyScripts);
gulp.task('clean', function(){
    return del('www/build');
});

Remember that gulp-concat package that we installed? We’re including it in the Gulp script here:

var gulpConcat = require('gulp-concat');

We’ll need to create a new Gulp task to be included in the build process. This is demonstrated through the extlibs task as follows:

gulp.task('extlibs', function() {
    return gulp.src('www/extlibs/*.js')
        .pipe(gulpConcat('external-libraries.js'))
        .pipe(gulp.dest('www/build/js'));
});

Every JavaScript file found in the www/extlibs directory will be merged into a single external-libraries.js file and placed in the www/build/js directory.

Inside the gulpfile.js file we need to add the new extlibs task to each of the watch and build tasks. This is demonstrated in the full source code mentioned higher up in the article.

With the Gulp file in working order, we can add the concatenated JavaScript file to the index file. Open the project’s www/index.html file and add the following:

<script src="build/js/external-libraries.js"></script>

It should be added right below the line that includes cordova.js.

Try it out. When you build your project, your JavaScript files should be added to the project now.

Conclusion

You just saw how to edit your project’s Gulp build script to add JavaScript libraries to your project. This is necessary when including JavaScript libraries that are not found in NPM because the default Ionic 2 build process may remove files that you place.

To give credit where credit is deserved, I used a solution in the Ionic 2 forums to assist with my version.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.