Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" in underscore is undefined after compiling with browserify and debowerify

So first.. I have next gulp task:

gulp.task('js', function() {
    browserify('./src/js/main.js')
        .bundle()
        .on('error', onError)
        .pipe( source('main.js') )
        .pipe( gulp.dest(path.build.js) );
});

and package.json:

{
  "browserify": {
    "transform": [
      ["babelify", { "presets": ["es2015"] }],
      "debowerify"
    ]
  },
}

I am importing Backbone in main.js (or only underscore... it doesn't matter)

import Backbone from 'backbone';

And in console I am getting error

Uncaught TypeError: Cannot read property '_' of undefined

I checked code and found that in underscore sources at start of library root is undefined

 // Establish the root object, `window` in the browser, or `exports` on the server.
  var root = this;

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

I think the problem is that debowerify or babelfy is wrapping code in some function. But also if I use node modules without debowerify all works fine. But I want to use bower.

So how to fix this problem?

like image 668
acidernt Avatar asked Dec 09 '15 13:12

acidernt


1 Answers

To any future visitors to this question,

this is similar to Underscore gives error when bundling with Webpack

The gist of the issue is that babel is probably running the underscore.js code, since underscore.js uses this, and in es6 this is undefined when outside of a function, naturally this._ fails.

In code I've fixed the issue by ensuring that babel does not run on node_modules.

like image 197
Patrick Avatar answered Oct 12 '22 12:10

Patrick