Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating npm package for both browser and node

I'm trying to create an npm package that could be used by web apps or other node modules.

If I were to only support browsers, I would just assign to window window.myExport = myExport; (unless there's a more modern way I'm not aware of?).

If I were to only support node modules, I would just use export, module.exports = myExport; (again, if there's a better way I'm not aware of, please let me know).

But I want to support both. Currently, what I'm doing is

var window, module;
if (window)
    window.myExport = myExport;
if (module)
    module.exports = myExport;

This looks very ugly, but works so far. What's a better approach? This is very lightweight node module, so I don't want to bring in some builder like webpack or something unless un-avoidable. I am already using babel though to create an es5 compatible version of my code, so if babel can solve this issue for me, that would work.

like image 282
junvar Avatar asked May 11 '26 02:05

junvar


1 Answers

If someone is already using npm to manage their dependencies than it is logical to assume that they will be using something like webpack or browserify that will allow them to import/require the module. It would be unusual for someone to download a library from NPM and manually include it in their page. I would also consider it a gross violation for an npm library to add itself to the window object. This could cause all sorts of issues especially if different versions of your library are included on the same page.

The real question is ES module exports or commonJS exports. Of which I currently favor CommonJS because ES modules are not natively implemented in nodejs yet so you have to use babel to easily import them.

like image 168
Deadron Avatar answered May 12 '26 16:05

Deadron