How to shim Buffer and crypto? #3126
-
I've read several discussions on how to shim nodejs modules such as Buffer and crypto, but so far I've never been able to fix the error I tried using several rollup plugins. The last one I used is I'm lost right now. Is there any way to make it work? BTW I'm using web3, so I can't drop this dependency. |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 24 replies
-
@mattiaz9 Ideally, the libraries you use in the browser shouldn't use node builtins. But in the meantime, you can use https://github.com/snowpackjs/rollup-plugin-polyfill-node to shim Buffer and other node builtins. In your vite.config.js, after import { defineConfig } from 'vite'
import polyfillNode from 'rollup-plugin-polyfill-node'
export default defineConfig({
plugins: [
polyfillNode()
],
optimizeDeps: {
exclude: ['web3'] // <= The libraries that need shimming should be excluded from dependency optimization.
}
}) I tested locally, and this setup is working for me import 'web3/dist/web3.min.js'
console.log(Web3) |
Beta Was this translation helpful? Give feedback.
-
I used https://github.com/feross/buffer and include it in my entry point like so:
Hope this works for others! |
Beta Was this translation helpful? Give feedback.
-
Here: #3817 (comment) |
Beta Was this translation helpful? Give feedback.
-
Another solution I found was to // buffer-shim.js
import { Buffer } from 'buffer'; // vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
optimizeDeps: {
esbuildOptions: {
inject: ['./buffer-shim.js'],
}
}
}) Of course, this means that every dep has an import for |
Beta Was this translation helpful? Give feedback.
-
Unfortunately neither @patak-dev nor @manzt's method is working for me to get crypto working in the browser. When I try to use a crypto function it silently fails in browser (works on server and worked previously in client when shimmed with webpack). |
Beta Was this translation helpful? Give feedback.
-
This works for me https://github.com/sodatea/vite-plugin-node-stdlib-browser |
Beta Was this translation helpful? Give feedback.
-
Late to the question, this was the only polyfill plugin that worked for shimming |
Beta Was this translation helpful? Give feedback.
I used https://github.com/feross/buffer and include it in my entry point like so:
Hope this works for others!