Environment detection: node.js or browser

后端 未结 8 1971
误落风尘
误落风尘 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:48

    I am not totally familiar with the Node environment and all its situations such as when Babel or WebPack is being used. But this is one way if you have code that runs in the browser vs in the Node console:

    if (this.window) {
      // inside browser
    
    } else {
      // inside Node
    
    }
    

提交回复
热议问题