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.
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) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With