D.F.F
D.F.F

Reputation: 961

unable to import web3

I am trying to add a nice GUI to my dapp while being utterly incompetent with everything related to web programming. The first version I did with webpack worked (but I did not understand how and why, really). I am now starting the second iteration, and for maximum simplicity, I decided to switch from webpack to vite (https://vitejs.dev/). After initializing the project as per the description given in the guide (https://vitejs.dev/guide/), I managed to get the 'hello vite' site running. Next I added Web3 with

npm install web3

and then I changed main.js from

import './style.css';

document.querySelector('#app').innerHTML = `
 <h1>Hello Vite!</h1>
 <a href="https://vitejs.dev/guide/features.html" target="_blank">Documentation</a>
`

to

import './style.css';
import Web3 from "web3";

document.querySelector('#app').innerHTML = `
  <h1>Hello Vite!</h1>
  <a href="https://vitejs.dev/guide/features.html" target="_blank">Documentation</a>
`

However, after changing this line, I get the following error:

Uncaught ReferenceError: process is not defined
    at node_modules/util/util.js (util.js:109)
    at __require2 (web3.js?v=5afc53e8:17)
    at node_modules/web3-core-requestmanager/lib/index.js (index.js:20)
    at __require2 (web3.js?v=5afc53e8:17)
    at node_modules/web3-core/lib/index.js (index.js:22)
    at __require2 (web3.js?v=5afc53e8:17)
    at node_modules/web3/lib/index.js (index.js:29)
    at __require2 (web3.js?v=5afc53e8:17)
    at dep:web3:1

Upvotes: 0

Views: 749

Answers (2)

eedris
eedris

Reputation: 1

This bug seems to be peculiar to vite.js. Install these dependencies:

browserify-zlib, events, process, stream-browserify, util

Add this to head the index.html file, just before you load any other script:

<script>window.global = window;</script>
<script type="module">
    import process from "process";
    import { Buffer } from "buffer";
    import EventEmitter from "events";
    
    window.Buffer = Buffer;
    window.process = process;
    window.EventEmitter = EventEmitter;
</script>
<!-- Other scripts -->

Edit your vite.config.js like so:

import vue from '@vitejs/plugin-vue'

export default {
  resolve: {
    alias: {
      process: "process/browser",
      stream: "stream-browserify",
      zlib: "browserify-zlib",
      util: 'util'
    }
  },
  plugins: [
    vue(),
  ]
}

And everything should work fine.

Upvotes: 0

Evert
Evert

Reputation: 99786

"process is not defined" implies you are trying to run Node.js-specific javascript in a browser. If web3 is meant to run in a browser, you would need something like webpack.

Upvotes: 1

Related Questions