D3.js : Uncaught TypeError: Cannot read property 'document' of undefined
Asked Answered
J

1

15

I'm having a really weird problem with d3.js initilization. In the d3.js script, at the very beginning, it tries to get var d3_document = this.document; but it pops the following error:

Uncaught TypeError: Cannot read property 'document' of undefined

when debugging, this.document returns undefined.

I'm using yo webapp to generate the project. It uses bower as package manager and gulp for the build process (that uses babel for the ES2015 features).

The funny thing is that I've tested it with xampp and it works fine!

I would appreciate some advice!Thnx!

Jervis answered 22/2, 2016 at 17:42 Comment(1)
Good detail about the setup. Without that detail, I couldn't have answered the question.Khosrow
K
17

It sounds like something (Babel, most likely) is inserting "use strict"; at the beginning of the D3 script file or combining it into another file with "use strict" at the top. That means this at global scope (or in a function called without a specific this) is no longer a reference to the global object, it's undefined. (Whereas in "loose" mode or in a function called with no specific this value, this at global scope is a reference to the global object, which is also accessible via the global variable `window1.)

You need to remove your d3.js from the list of scripts being transformed by Babel and just include it as-is. Assuming you're using the normal d3.js file, it looks like this:

!function() {
  var d3 = {
    version: "3.5.16"
  };
  var d3_arraySlice = [].slice, d3_array = function(list) {
    return d3_arraySlice.call(list);
  };
  var d3_document = this.document;
  // ...
  // ...
  // ...lots of stuff here...
  // ...
  // ...
}();

That relies on being run in loose mode.

Khosrow answered 22/2, 2016 at 17:49 Comment(1)
Thnx, definitely it's babel that appends 'use restrict' to the scripts. For anyone having this same issue, go here to know how to resolve it in babel 5 and babel 6.Jervis

© 2022 - 2024 — McMap. All rights reserved.