【问题标题】:Web3 Require is not definedWeb3 Require 未定义
【发布时间】:2021-09-15 19:48:58
【问题描述】:

您好,我正在尝试将 Web3 链接到我的 html。我正在使用这个https://github.com/ChainSafe/web3.js?source=post_page-----e3fbe89111c3---------------------- 链接。

这是我在 html 文件中的代码

<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
        <script src="app.js"></script>

这是我在 app.js 中的代码

// In Node.js
const Web3 = require('web3');

let web3 = new Web3('ws://localhost:8546');
console.log(web3);

我一直在尝试用谷歌搜索答案,但似乎找不到我的问题的答案。

【问题讨论】:

    标签: javascript node.js web3js


    【解决方案1】:
    // In Node.js
    const Web3 = require('web3');
    

    看看那条评论。你不是在 Node.js 中。

    您正在加载带有脚本元素的 web3:

    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    

    ...所以不要尝试使用为 Node.js 设计的方法在 Web 浏览器中加载它。

    (如果您想使用该方法,则可以删除脚本元素并使用 Parcel 或 Webpack 等工具将 JS 转换为浏览器友好的内容)。

    【讨论】:

    • 你是什么意思“看看那个评论。你不在 Node.js 中。”。我已经安装了 node.js。我很困惑。
    • 您有一个包含脚本元素的 HTML 文档。那是网络浏览器运行的东西。它不是 Node.js 运行的东西。如果 Node.js 永远不会靠近你的代码,那么安装 Node.js 是没有意义的。
    • @AngeloTree:Node.js 是一个独立的 JS 运行时。此代码在浏览器中运行。
    • @AngeloTree 您可能正在使用 Node 包管理器 (NPM) 来安装依赖项,但您没有运行 Node.js。我希望区别很明显。
    猜你喜欢
    • 2019-09-01
    • 2018-12-05
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 2014-01-03
    • 2014-03-16
    • 1970-01-01
    相关资源
    最近更新 更多