UMD javascript module which also works in strict mode

≯℡__Kan透↙ 提交于 2019-12-13 02:15:02

问题


I'm having trouble rewriting this to work in 'strict' mode. Since 'this' is not defined explicitly I'm getting jshint errors on compile. I'm thinking my brain is just not thinking abstractly enough to find a creative solution. Any help would be appreciated. Code adapted from the Universal Module Definition Github repo: https://github.com/umdjs/umd/blob/master/returnExports.js

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
    // AMD Module
        define([], factory);
    } else if (typeof module === 'object' && module.exports) {
    // Node Module
        module.exports = factory();
    } else {
    // Browser Global
        root.returnExports = factory();
  }
}(this, function () {
    return {};
}));

回答1:


Looking at your code, I see that root is only actually used in the case that you are in a browser, which simplifies things.

That means that we can replace this with the following expression:

typeof window !== "undefined" ? window : undefined

This is valid in strict mode (I tried it in Node, it returns undefined, no errors), and JSHint.com allowed it.

If you need the global object in other cases as well, you can chain the ternary expressions.



来源:https://stackoverflow.com/questions/32012589/umd-javascript-module-which-also-works-in-strict-mode

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