Alireza
Alireza

Reputation: 5523

How to fix a library's dependency on node-only modules

This is about https://github.com/ecadlabs/taquito/. This library usable from both node applications, and browser applications. But we assume the majority should be using it from the browser.

When added to an angular project, I get this error in developer tools:

browser-external:buffer:9 Module "buffer" has been externalized for browser compatibility. Cannot access "buffer.Buffer" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details

Similar errors in other frontend stacks.

I tried:

  1. changing our rollup config to polyfill these,
  2. tried parcel (that says it does this polyfill automatically, with no configuration)
  3. tried microbundle

no matter what I do, I cannot remove this warning.

This dependency on buffer probably comes from one of our dependencies.

What is the right way to fix this?

Please note that I need to fix my library, so that users can consume it without needing any polyfills

EDIT: Being more specific:

C--dependeson-->B--depends on-->A--uses-->buffer

Now if I don't do anything, people need to polyfill their apps (C). I want to do that in B. So that it's done once, and I create a good developer experience for them. We have complete control over B, but no control over A and we want to make things work out of box for people doing C

Upvotes: 0

Views: 444

Answers (2)

Evert
Evert

Reputation: 99728

Also a library author. For me one of my goals for all my (frontend) libraries is that they are small and very low in dependencies. Important for Node, but way more important for browsers.

By far the best way to universally fix this, is to try to figure out which of your dependencies uses Buffer, and remove this dependency.

Many NPM packages exist that are frontend-friendly. If they use Buffer, they are explicitly not and inflate your bundle. Sometimes you can simply inline whatever you needed from a dependency, and sometimes you can find alternative. If the functionality the dependency provided was somewhat small, just copy it in and reduce your dependency tree.

Upvotes: 0

Dennis
Dennis

Reputation: 4017

The error message you're encountering indicates that the library you're using relies on Node.js-specific features (in this case, the buffer module), which are not natively available in the browser environment. This situation is common when using libraries that are built to support both Node.js and the frontend, but certain Node.js modules need polyfills or equivalents to work in the browser.

The most straightforward way is to use a polyfill like feross/buffer which is specifically designed to mimic the Buffer API in the browser.

Upvotes: 0

Related Questions