Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect when browserify is being run?

Tags:

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

like image 765
samol Avatar asked Apr 13 '14 02:04

samol


People also ask

When should I use Browserify?

Browserify solves the problems of having too many JS files referenced in your HTML, inability to use Node modules in the browser, and inability to reference your own modules in your own code. Watchify streamlines the process of bundling your files and will make a change every time you change a JS file in your project.

What is Browserify in NPM?

Browserify is an open-source JavaScript bundler tool that allows developers to write and use Node. js-style modules that compile for use in the browser.

What are two Browserify functions?

Hello World With Browserify With Browserify you can write code that uses require in the same way that you would use it in Node. Browserify parses the AST for require() calls to traverse the entire dependency graph of your project. Drop a single <script> tag into your html and you're done!


2 Answers

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.

like image 133
amwinter Avatar answered Oct 06 '22 09:10

amwinter


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.

like image 20
substack Avatar answered Oct 06 '22 10:10

substack