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
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.
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.
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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With