【问题标题】:在 NextJS 应用程序中导入 web3 时出现 Netlify 构建错误 - '错误:无法解析 'electron' in...'(Getting Netlify build error when importing web3 in NextJS application - 'Error: Can't resolve 'electron' in...')
【发布时间】:2021-12-21 14:31:49
【问题描述】:

我正在构建一个使用 web3 与以太坊智能合约交互的网页。每当我将 web3 导入页面时,我都会在 Netlify 构建中遇到错误:

9:54:39 PM: ModuleNotFoundError: Module not found: Error: Can't resolve 'electron' in '/opt/build/repo/node_modules/swarm-js/node_modules/got'
9:54:39 PM: > Build error occurred
9:54:39 PM: Error: > Build failed because of webpack errors

我可以通过将 web3 导入添加到页面来重现此错误而不是简单地得到它:

import web3 from '../ethereum/web3'

上面的代码只是从另一个文件中导出一个实例化的 web3 实例:

import Web3 from "web3";
 
let web3;
 
if (typeof window !== "undefined" && typeof window.ethereum !== "undefined") {
  // We are in the browser and metamask is running.
  window.ethereum.request({ method: "eth_requestAccounts" });
  web3 = new Web3(window.ethereum);
} else {
  // We are on the server *OR* the user is not running metamask
  const provider = new Web3.providers.HttpProvider(
    "https://mainnet.infura.io/v3/{INFURA_KEY}"
  );
  web3 = new Web3(provider);
}
 
export default web3;

我认为这可能与 web3 只能在浏览器中运行和 NextJS 执行一些 s-s-r 有关,但我不能完全解决这个问题。这是我的完整页面代码:

import Head from 'next/head'
import Header from '../components/Header'
import Menu from '../components/Menu'
import Footer from '../components/Footer'
import web3 from '../ethereum/web3'
const compiledFaucet = require('../ethereum/contracts/Faucet.json')


export default function Faucet() {
  const getICHCHandler = () => {
    console.log('dripping ICHC from faucet')
  }

  return (
    
I Can Has Cheezburger Token {/* Global site tag (gtag.js) - Google Analytics */}