简体   繁体   中英

Trouble access node_modules on javascript

I have confusion about access node_modules that can be used in JavaScript. for this does anyone can give an example to call modul.export contained in the folder node_module (after install packet with NPM - nodejs) ?

tree structure file : folder ethereum any folder node_modules , file index.html (for call module.export) , package-lock.json , package.json

package.json file : enter link description here

so this way, I've installed "npm install web3". Now, when I call a function from web3 like for example in a program like this :

var Web3=require('web3');
  if (typeof web3 !== 'undefined') {
        web3 = new Web3(web3.currentProvider);
    } else {
        web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/metamask"));
    }
  console.log(web3);

Then output errors like this : enter image description here

If I understand correctly, you are missing a big piece of the puzzle here.

You need to compile your code for the browser to be able to run it. Try reading up on this question

The web3 package can either be installed through npm with npm install web3 or is exposed as a global web3 if you import it like:

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>

It can either be run as a global exposed by the <script></script> tag or as a node package that needs to be bundled first.

Your error code require is not defined tells you that node is not running your code, but something else is consuming your code. Try to bundle your code to something the browser understands, or only use the global web3 to interact with the package.

Read more about bundles here: https://docs.npmjs.com/getting-started/packages

您可以使用Browserify要求Node提供模块。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM