how to avoid Uncaught ReferenceError

*爱你&永不变心* 提交于 2021-02-08 12:16:56

问题


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.


回答1:


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) {
}


来源:https://stackoverflow.com/questions/17967852/how-to-avoid-uncaught-referenceerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!