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.
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.
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