Search code examples
node.jsgulpbrowserifyshimbrowserify-shim

Browserify-shim with gulp


I'm testing out gulp with browserify and I'm trying to get the following working:

I have a file called export.js, which depends on another file called export2.js.

export.js

module.exports = function(){ 
    console.log("test export"); 
}; 

export2.js

module.exports = function(){
    console.log("export 2"); 
}

I have another file called app.js, where I define the following code:

var e = require("e"); 

I tried to define the dependency by using a shim.
The related code in my package.json looks like this:

  "browserify-shim": { 
        "jquery": "$", 
        "public/src/js/home/export.js":  { 
            "exports": "e", 
            "depends": [ 
              "public/src/js/home/export2.js"
            ]
        }
  }, 
  "browserify": {
      "transform": [
          "browserify-shim" 
      ]
  }, 

The path should be correct.

My gulp file defines:

//Uglifies scripts 
gulp.task("uglify-scripts", function(){ 
    return browserify({ entries:["public/src/js/home/app.js"]})
            .bundle()
            .pipe(source("bundle.js"))  // gives streaming vinyl file object
            .pipe(buffer())             //convert from streaming to buffered vinyl file object
            .pipe(uglify())             //gulp-uglify 
            .pipe(gulp.dest("public/src/js/home/dist"))
            .pipe(livereload()); 

}); 

I tested the task before (uglification of app.js without the dependency), it runs fine.
However, with the shim defined, I still receive a message in the console mentioning

Cannot find module 'e'

Can you see what is going wrong or what I have misunderstood?


Solution

  • Shims are for modules that don't support commonJS. You can simply define these dependencies explicitly:

    export.js

    var e2 = require('./export2.js');
    module.exports = function(){ 
        console.log("test export"); 
    };
    

    export2.js

    module.exports = function(){
        console.log("export 2"); 
    };
    

    app.js

    var e = require('public/src/js/home/export.js');