how to detect when browserify is being run?

后端 未结 3 1829
离开以前
离开以前 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.

提交回复
热议问题