how to detect when browserify is being run?

后端 未结 3 1658
离开以前
离开以前 2021-02-02 12:53

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

相关标签:
3条回答
  • 2021-02-02 13:01

    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.

    0 讨论(0)
  • 2021-02-02 13:02

    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.

    0 讨论(0)
  • 2021-02-02 13:09

    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!

    0 讨论(0)
提交回复
热议问题