运行Hardhat部署命令时出现TypeError问题求助
部署Hardhat合约时TypeError问题排查
问题场景
执行部署命令时触发错误:
npx hardhat run scripts/deploy.ts --network localhost
错误日志
(base) page Feb 27 4:54 ~/.../with typescript/my-first-dapp/smart-contract > npx hardhat run scripts/deploy.ts --network localhost TypeError: Cannot read properties of undefined (reading 'prototype') at registerCustomInspection (/home/page/Desktop/pages/with typescript/my-first-dapp/smart-contract/node_modules/@nomiclabs/hardhat-ethers/src/internal/index.ts:22:13) at /home/page/Desktop/pages/with typescript/my-first-dapp/smart-contract/node_modules/@nomiclabs/hardhat-ethers/src/internal/index.ts:34:5 at getRealTarget (/home/page/Desktop/pages/with typescript/my-first-dapp/smart-contract/node_modules/hardhat/src/internal/util/lazy.ts:112:22) at Object.get (/home/page/Desktop/pages/with typescript/my-first-dapp/smart-contract/node_modules/hardhat/src/internal/util/lazy.ts:185:26) at main (/home/page/Desktop/pages/with typescript/my-first-dapp/smart-contract/scripts/deploy.ts:28:36) at Object.<anonymous> (/home/page/Desktop/pages/with typescript/my-first-dapp/smart-contract/scripts/deploy.ts:43:1) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Module.m._compile (/home/page/Desktop/pages/with typescript/my-first-dapp/smart-contract/node_modules/ts-node/src/index.ts:1618:23) at Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Object.require.extensions.<computed> [as .ts] (/home/page/Desktop/pages/with typescript/my-first-dapp/smart-contract/node_modules/ts-node/src/index.ts:1621:12)
部署脚本代码
const hre = require("hardhat"); async function main() { const StackUp = await hre.ethers.getContractFactory("StackUp"); const stackUp = await StackUp.deploy(); await stackUp.deployed(); console.log("stackUp deployed to:", stackUp.address); let adminAddr = await stackUp.admin(); console.log("admin address:", adminAddr); await stackUp.createQuest("Introduction to Hardhat", 2, 600); await stackUp.createQuest("Unit Testing with Hardhat", 4, 500); await stackUp.createQuest("Debugging and Deploying with Hardhat", 5, 400); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); });
可能原因及解决步骤
1. 依赖版本不兼容
这是最常见的原因,hardhat、@nomiclabs/hardhat-ethers和ethers版本错位会导致内部API调用失败。
- 打开
package.json,确保版本匹配,推荐稳定组合:hardhat: ^2.19.0@nomiclabs/hardhat-ethers: ^2.2.3ethers: ^5.7.2(注意:ethers v6与hardhat-ethers v2.x不兼容,必须用v5系列)
- 修改后执行
npm install重新安装依赖。
2. 依赖缓存或安装损坏
node_modules可能存在缺失或损坏的文件,导致模块加载异常:
rm -rf node_modules package-lock.json yarn.lock npm cache clean --force npm install
3. Hardhat配置缺失插件
检查hardhat.config.ts(或.js)是否正确引入插件:
// TypeScript格式 import "@nomiclabs/hardhat-ethers"; // CommonJS格式 require("@nomiclabs/hardhat-ethers");
4. 本地节点状态异常
确保npx hardhat node已启动,且网络配置正确:
// hardhat.config.ts中的网络配置 networks: { localhost: { url: "http://127.0.0.1:8545" } }
内容的提问来源于stack exchange,提问作者CCDev
相关产品推荐
相关产品推荐

