Nate
Nate

Reputation: 28414

Error when loading jQuery: "Uncaught TypeError: Cannot read property 'exports' of null "

I'm working on a bookmarklet that requires jQuery and have run into a problem on a website.

When I try loading jQuery on toysrus.com, using this code:

var element = document.createElement("script");
element.onload=function() {
    jQuery.noConflict();
}
element.src = "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js";
document.body.appendChild(element);

This error is shown in the console:

Uncaught TypeError: Cannot read property 'exports' of null 

Screenshot.

The error points to the second line of code in the file:

if ( typeof module === "object" && typeof module.exports === "object" ) {

From what I understand, it's perfectly fine to load jQuery more than once as long as noConflict() is called, which I'm doing, and this error only seems to be happening on this one website.

Why is the error occurring and what can I do to fix it?

UPDATE:

Running the code from the line the error is occurring on in the browser causes the same error:

typeof module === "object" && typeof module.exports === "object"

Output:

TypeError: Cannot read property 'exports' of null

I'm confused why the error is being thrown, since if module.exports doesn't exist, should the console just output undefined?

Upvotes: 1

Views: 1430

Answers (1)

dherman
dherman

Reputation: 2892

It's arguably a bug in jQuery, you should file a bug for it.

For historical reasons, typeof null in javascript results in object, so their check would throw the exact exception that you're seeing in the case that module is null.

If you inspect the value of window.module on that site, you'll see that it is null, so it's hitting the case that I'm referring to.

You could even make a pull request ( after filing the bug! ) since the fix is just to change the check to something like

typeof module === "object" && module && typeof module.exports === "object"

Upvotes: 3

Related Questions