randombytes icon indicating copy to clipboard operation
randombytes copied to clipboard

add `module` export

Open mesqueeb opened this issue 6 years ago • 4 comments

Adding a module export makes rollup and webpack automatically use that package over the NodeJS one when importing it into a project.

mesqueeb avatar Feb 22 '19 08:02 mesqueeb

is that actually what we want? the aim here is for this package to always be used in the browser and never in node

calvinmetcalf avatar Feb 22 '19 13:02 calvinmetcalf

@calvinmetcalf Of course. What this package does correct is that when I try to use it in node and do:

const randomBytes = require('randombytes')

it will use the "main": "index.js" file from package.json. Which is just the nodeJS one, so this is good.

The thing is that if I build a web-app and I use NPM to install this dependency and I do:

import randomBytes from 'randombytes'

then, to my knowledge (and this thread) Rollup and Webpack would import the "module": "browser.js" file if this is defined in the package.json. If not I think it might go for the "main": "index.js" which is exactly what we want to avoid.

If I have a web-app which is an SPA hosted on a server unrelated to NodeJS, what will happen is that Rollup or Webpack, when bundling my JS, will start to polyfill native NodeJS functionality for me (like crypto) which is exactly what we want to avoid by using this package. 😉

How I learned to do package.json is:

  • main is for NodeJS, so best export in the commonJS way
  • module is for importing through import x from 'x' and is usually an index file that exports with export default something or export {somthings}
  • module further is what will be picked up by Rollup/Webpack when you bundle a web-app and you use ESM import methods

But please, correct me if I'm wrong, because I think there are a lot of confusing things related to import/require, webpack/rollup, web/browser/node, etc.etc. and it's difficult for most people to understand how everything works 100%. I'm probably wrong here or there. 😃 For me it's a lot of information I just picked up here and there, and no-where did I find one guide that explains all of this in an easy way. 😭

mesqueeb avatar Feb 23 '19 06:02 mesqueeb

I believe that webpack honers the browser field, have you tested to see if this is actually a problem for you ?

calvinmetcalf avatar Feb 25 '19 13:02 calvinmetcalf

@calvinmetcalf I believe so yes. I'm using rollup in most cases though. I will check rollup and come back here to note on which entry it's picking up.

mesqueeb avatar Feb 26 '19 00:02 mesqueeb