Environment detection: node.js or browser

后端 未结 8 1954
误落风尘
误落风尘 2020-11-29 20:54

I\'m developping a JS-app that needs to work both on the client side and the server side (in Javascript on a browser and in Node.js), and I would like to be able to reuse th

8条回答
  •  隐瞒了意图╮
    2020-11-29 21:36

    I know this is a late answer to a (1.5 year) old question but why not copy jQuery's source code?

    if (typeof module === "object" && typeof module.exports === "object") {
      // node
    }
    
    if (typeof window !== "undefined" && typeof window.document !== "undefined") {
      // browser
    }
    

    Good luck.

提交回复
热议问题