简体   繁体   English

无法访问JavaScript上的node_modules

[英]Trouble access node_modules on javascript

I have confusion about access node_modules that can be used in JavaScript. 我对可在JavaScript中使用的访问node_modules感到困惑。 for this does anyone can give an example to call modul.export contained in the folder node_module (after install packet with NPM - nodejs) ? 为此,有谁能举一个例子来调用文件夹node_module中包含的modul.export(在使用NPM-nodejs安装数据包之后)?

tree structure file : folder ethereum any folder node_modules , file index.html (for call module.export) , package-lock.json , package.json 树状结构文件:文件夹以太坊任何文件夹node_modules,文件index.html(用于调用module.export),package-lock.json,package.json

package.json file : enter link description here package.json文件: 在此处输入链接描述

so this way, I've installed "npm install web3". 这样,我已经安装了“ npm install web3”。 Now, when I call a function from web3 like for example in a program like this : 现在,当我从web3调用一个函数时,例如在这样的程序中:

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: web3软件包既可以通过npmnpm install web3一起npm install web3也可以通过以下方式作为全局web3公开:

<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. 它可以作为<script></script>标记公开的全局变量运行,也可以作为首先需要捆绑的node程序包运行。

Your error code require is not defined tells you that node is not running your code, but something else is consuming your code. 错误代码require is not defined告诉您node未在运行您的代码,但是其他原因正在占用您的代码。 Try to bundle your code to something the browser understands, or only use the global web3 to interact with the package. 尝试将您的代码绑定到浏览器可以理解的内容,或者仅使用全局web3与程序包进行交互。

Read more about bundles here: https://docs.npmjs.com/getting-started/packages 在此处阅读有关捆绑包的更多信息: https : //docs.npmjs.com/getting-started/packages

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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