Aleix
Aleix

Reputation: 497

Error while requiring external library with browserify (this = undefined)

I'm trying to require the library Chart.js with Browserify (tbh it's development environment with gulp, browserify and some other stuff that I barely know how it works togheter):

'use strict';
var angular = require('angular');
require('angular-ui-router');
require('./templates');
require('./controllers/_index');
require('./services/_index');
require('./directives/_index');
window.gauge = require('./vendors/gauge');

//this is what i'm trying to require
window.chartjs = require('./vendors/chart');

angular.element(document).ready(function() {
  var requires = [
    'ui.router',
    'templates',
    'app.controllers',
    'app.services',
    'app.directives'
  ];
  window.app = angular.module('app', requires);
  angular.module('app').constant('AppSettings', require('./constants'));
  angular.module('app').config(require('./routes'));
  angular.module('app').config(require('./PostFix'));
  angular.module('app').run(require('./on_run'));
  angular.bootstrap(document, ['app']);
});

Tbh it did work well with window.gauge = require('./vendors/gauge'); but when I require vendors/chart.js it throws this error:

undefined                                                     // chart.js:4 
Uncaught TypeError: Cannot read property 'Chart' of undefined // chart.js:4 

And here is those lines in the chart.js file:

(function(){

 "use strict";

  console.log(this); <------ outputs the "undefined"

  var root = this,
    previous = root.Chart; <----- fails, as "root" doesn't exist

It's weird, because when I add chart.js using <script></script> that console.log(this) outputs the window object/scope, but when executed from browserify, it's undefined, that's why the chart.js fails.

I'm a total newb with browserify/node/gulp, but I tried different stuff such as:

I'm guessing that somehow I have to attach that script to an object or something so this would not be undefined when executed, but I'm failing to find the way.

Upvotes: 0

Views: 898

Answers (1)

Aleix
Aleix

Reputation: 497

I already solved it. The problem was a browserify transform called Babelify. I still don't know why Babel was doing that, but I didn't need it anyway so I just disabled it and that was it. Just posting it here in case it happens to someone else.

Upvotes: 1

Related Questions