Web3.js – Resolving ‘Web3 is Not Defined’ Error

web3js

I'm trying to create a npm module with functions for interact with the ethereum blockchain, for the interaction i'm using the web3js API and i will put this module inside the my new module.

In my packaje.json i put this:

"dependencies": {
"web3": "^0.18.3"
}

I'm installing the module with the option –save and in the folder node_module i have all the modules required for web3 and this one installed.

So when i try to test the functionality of my new module i obtain this error:

web3 = new Web3(new Web3.providers.HttpProvider("http://ropsten.infura.io/")
);          ^
ReferenceError: Web3 is not defined

Why is happening this if i have installed the module? Some idea?

More information:

I call my new module with:

 var ether = require('./lib/newmodule.js');

Inside the newmodule.jsi have this for the conection:

if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider("http://ropsten.infura.io/"));   
    if(!web3.isConnected())
        console.log("not connected");
    else
        console.log("connected");
}

and this for use the module:

module.exports = methods;

And inside methods one methode for print the data and test if work or not the js. In a other Dapp project the newmodule.js works fine, but the web3js is installed by meteor.js so i think's i'm not doing something well with the web3.js installation or building the structure of the module.

Best Answer

Posting solution from discussions in comments:

The Web3 is not defined because you need to import it where you want to use it, installing web3 alone is not sufficient.

In order to use web3 in you project,follow the steps;

  1. Install web3 using any package manager like npm or bower:
    npm install web3 or bower install web3
  2. Import the web3 liberary in js where you want to use it by using:

    Web3 = require('web3')

You can find details here npm-web3.