Search code examples
javascriptnode.jsnpmgulpbrowserify

Navigo not defined when using Browserify with gulp


I can't get Navigo (npm package) to work with Browserify and Gulp

My file structure (only including relevant stuff)

-index.html
-build
    -js
        -modules.js
        -routing.js
-js
    -modules.js

My bundle task in my gulpfile.js that uses browserify to be able to use Navigo in my actual routing.js file

gulp.task('bundlemods', function() {
    var bundleMods = browserify('./js/modules.js')
    .bundle()
    .on('error', console.error)
    .pipe(source('modules.js'))
    .pipe(gulp.dest('./build/js'));
});

Which outputs the following modules.js file

Then in my routing.js I'm just trying to use Navigo as following:

function initRouting() {
    var rootUrl = null;
    var useHash = false;
    var router = new Navigo(rootUrl, useHash);

    router.on(function () {
        runHome();
    })
    .resolve();
}

However, this yields the error Uncaught ReferenceError: Navigo is not defined

Also this is how my index.html file looks (relevant parts once again)

<!doctype html>
<html>
<head>
/* stuff */
</head>
<body>
    <main>
        /* stuff */
    </main>
    <script src="build/js/modules.js"></script>
    <script src="build/js/routing.js"></script>
    /* other scripts */
</body>
</html>

What is the reason it is still undefined? How do I actually use Navigo once I've used Browserify to generate my modules file? Does it have something to do with global scopes or something else I'm missing?


Solution

  • Of course browserify prevent variables to leak in global scope. If you want to have it gloabally available you should explicitly attach it to global scope:

    Navigo = require('navigo');
    

    not using var key will attach Navigo var to global scope and when you browserify it, your global will be window and Navigo is available from anywhere.

    If you don't want pollute global scope then you could just require it in routing.js:

    var Navigo = require('navigo');
    function initRouting() {
        var rootUrl = null;
        var useHash = false;
        var router = new Navigo(rootUrl, useHash);
    
        router.on(function () {
            runHome();
        })
        .resolve();
    }
    

    and then browserify this file instead.