This is an issue that I’ve seen a lot of confusion over, and even seasoned JavaScript developers might have missed some of its subtleties. So I thought it was worth a short tutorial.
Rollup and process.env.BROWSER
Basic example
“browser” field, how I love thee
If you search through the Browserify or Webpack documentation for tips on how to solve this problem, you may eventually discover node-browser-resolve. This is a specification for a "browser" field inside of package.json, which can be used to define modules that should be swapped out when building for the browser.
Using this technique, we can add the following to our package.json:
{ /* ... */ "browser": { "./index.js": "./browser.js" } }
And then separate the functions into two different files, index.js and browser.js:
// index.js module.exports = function (string) { return Buffer.from(string, 'binary').toString('base64'); };
// browser.js module.exports = function (string) { return btoa(string); };
After this fix, Browserify and Webpack provide much more reasonable bundles: Browserify’s is 511 bytes minified (315 min+gz), and Webpack’s is 550 bytes minified (297 min+gz).
Advanced techniques
The direct "browser" method works well, but for larger projects I find that it introduces an awkward coupling between package.json and the codebase. For instance, our package.json could quickly end up looking like this:















