how to detect when browserify is being run?

荒凉一梦 提交于 2019-12-02 21:35:16

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.

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.

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!

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