how to detect when browserify is being run?

2020-05-20 06:08发布

问题:

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!