Make your npm package work on both Node.js and browser

Nir Hadassi
Aspecto
Published in
2 min readDec 17, 2019

How to avoid native node modules (like fs, child_process, etc..) crashing your app while running on the browser (this post is not about UMD!)

I recently worked on an npm package that is supposed to be consumed on both Node.js environment and the browser (using React/Angular/etc..).

Things started getting complicated when the node branch of the code needed to require native Node.js packages — like fs.

Consider the following (simplified) code:

When testing the module on my React + Webpack app, the app crashed:

This happened even though the node-handler file wasn’t executed, this is due to Webpack nature of creating a bundle containing all the code.

Step 1: Postpone your requires

Instead of requiring fs in the global scope, we can require it only where we actually need it, that way we won’t require it when running in the browser:

Cool! Our React app is not crashing anymore! But we do get an annoying compilation warning right now:

While we can live with a warning ⚠️ , our end users will probably won’t like this too much and will end up not installing our package.

Step 2: eval your require

This is not the most elegant solution (to say the least..), but it’s keeping Webpack quiet and your end users happy. Instead of using require('fs'), we’re gonna use eval('require')('fs'):

Good luck! May you be blessed with tons of stars 🌟

--

--