developit / microbundle

📦 Zero-configuration bundler for tiny modules.
https://npm.im/microbundle
MIT License
8.03k stars 362 forks source link

Cannot use module that use native node-js modules #972

Closed multivoltage closed 2 years ago

multivoltage commented 2 years ago

My library for the web use scripty for encode a password.

This module use inside 'crypto' of node js platform.

I build my lib with microbundle build --external none -f modern and it add "axios" and "scripty" because I put these deps on dependencies. This is correct, but it fails during usage of produced build because of "crypto" mode. In fact my browser try to search import e from 'crypto

How can manage library that use native node module?

developit commented 2 years ago

@multivoltage I believe you can use https://github.com/crypto-browserify/crypto-browserify:

  "build": "microbundle --external none -f modern --alias crypto=crypto-browserify"
multivoltage commented 2 years ago

@developit This assume that 'crypto-browserify' is installed in my lib right? So what the purpose to create an alias if It should be enough to install on dependencies?. From microbundle (or rollup under the hood) I thought that there was a sort of (browserify) of all modules. I tried browserify 'scripty' and it worked (but I was not able to work inside my lib

developit commented 2 years ago

Yes, this assumes your module has a dependency on crypto-browserify.

Microbundle doesn't do magic aliasing for web, because doing so produces huge bundles. FWIW both Webpack and Rollup have also stopped doing this by default - it was a nice way to transition Node libraries to the browser, but ultimately the results are problematic.

The reason for the alias is just to tell microbundle that it should replace require('crypto') with require('crypto-browserify'). There are some other ways to do it, this is just generally the easiest.

multivoltage commented 2 years ago

@developit Thanks a lot for explain. I tried now with a empy creare-react-app and and run a build. I have the same problem. But error explain that there is a BREAKING CHANGE with webpack >=5. LIke @developit said, webpack < 5 used to include polifyll under the hood. I think rollup do the same thing. Hope that if someone read that issue, he will apply developit solution and undestand problem.