how to detect when browserify is being run?

混江龙づ霸主 提交于 2019-12-03 06:57:09

问题


I have a library that I want to use in both client side and server side. However, because request is not compatible with browserify, when compiling using browserify, I need to use a different library called browser-request

if (inNodejsRuntime) {
  var request = require('request');
} else if (isBrowserifyRuntime) {
  var request = require('browser-request');
}

How do I go about detecting when browserifying is running vs when it is inside node


回答1:


If you are just doing a simple module swap with compatible APIs you should use the browser field in package.json. So for your example, just do

var request = require('request')

like before and then in the package.json put:

{
  "browser": {
    "request": "browser-request"
  }
}

This way in the browser you will get browser-request instead of request when you require('request').

What you shouldn't do is require both modules with a runtime check for the presence of window or some similar property. This is because you will get browser-request AND request bundled into your frontend code, even if you only actually use browser-request, resulting in a needlessly inflated file size.




回答2:


The accepted answer is correct. But if you got here by googling 'detect browserify' and want the more general answer, browserify automatically transforms the node-provided global process. You can use:

process.browser

which will be true in the browser, undefined in node.




回答3:


I found the answer:

if (typeof window === 'undefined') {
  var request = require('request');
} else {
  var request = require('browser-request');
}

Superagent is also looking like a very good alternative!



来源:https://stackoverflow.com/questions/23038483/how-to-detect-when-browserify-is-being-run

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