Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid Uncaught ReferenceError

I have the below module export in my javascript file, so that I can access it from node.js based build setup (grunt, require..).

    ....
if(module && module.exports) {
        module.exports = m;
    }

when I use the same file in browser, it gives error

Uncaught ReferenceError: module is not defined const.js:49
(anonymous function)

I do not use node as backend. how can I avoid this error? That is, I need to export m so that require it during build (node based), but works standalone in browser.

why doesn't the browser treat the variable module as undefined and not throw any error?

Thanks.

like image 463
bsr Avatar asked Jul 31 '13 10:07

bsr


1 Answers

Test typeof module !== "undefined" instead of module

why doesn't the browser treat the variable module as undefined and not throw any error?

Because, as well as being undefined, it is also undeclared. This is an excellent feature for throwing an error when you make a typo in a variable name. For example, it is better for the following to error instead of being treated as false:

var loose = true;
if (lose) {
}
like image 142
Quentin Avatar answered Oct 25 '22 22:10

Quentin