You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署合约时遇Module not found错误:无法找到指定合约JSON文件

合约交互「无法找到模块」错误排查与解决

问题场景

执行合约交互脚本时触发模块找不到错误,脚本文件及报错信息如下:

交互脚本 interact.js 内容

const { ethers } = require("hardhat");

const API_KEY = process.env.API_KEY; // 从Alchemy获取
const CONTRACT_ADDRESS = process.env.CONTRACT; // 已部署合约地址
const PRIVATE_KEY = process.env.PRIVATE_KEY; // MetaMask私钥

const contract = require('.../Hello-World/artifacts/contracts/Hello-World.sol/HelloWorld.json');

// Alchemy Provider
const alchemyProvider = new ethers.providers.AlchemyProvider(network="goerli", API_KEY);

// 签名者
const signer = new ethers.Wallet(PRIVATE_KEY, alchemyProvider);

// 合约实例
const helloWorldContract = new ethers.Contract(CONTRACT_ADDRESS, contract.abi, signer);

async function main() {
    const message = await helloWorldContract.message();
    console.log("当前消息: " + message);

    const tx = await helloWorldContract.update("Good Bye, World!");
    await tx.wait();

    const nmessage = await helloWorldContract.message();
    console.log("更新后消息: " + nmessage);
}

main()
.then(() => process.exit(0))
.catch(error => {
  console.error(error);
  process.exit(1);
});

执行命令

npx hardhat run scripts/interact.js --network goerli

错误信息

Error: Cannot find module '.../Hello-World/artifacts/contracts/Hello-World.sol/HelloWorld.json'
Require stack:

  • C:\Users\ASUS\Hello-World\scripts\interact.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object. (C:\Users\ASUS\Hello-World\scripts\interact.js:7:18)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)

解决方法

1. 修正路径语法错误

脚本中使用了无效的相对路径写法.../,相对路径中表示上级目录仅需两个点../。根据你的文件结构(脚本位于scripts目录,artifacts在项目根目录),正确路径应为:

const contract = require('../artifacts/contracts/Hello-World.sol/HelloWorld.json');

2. 确保合约已编译生成artifacts文件

如果路径修正后仍报错,先执行编译命令生成必要的合约JSON文件:

npx hardhat compile

编译完成后,检查Hello-World/artifacts/contracts/Hello-World.sol/HelloWorld.json是否存在。

3. 验证Hardhat配置(可选)

若编译后仍未生成目标文件,检查hardhat.config.js中的路径配置,确保artifacts目录未被错误修改:

module.exports = {
  paths: {
    artifacts: "./artifacts", // 默认路径,保持此配置即可
  },
  // 其他配置项...
};

内容的提问来源于stack exchange,提问作者David Cobbs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:45:39