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

NestJS集成Hardhat报错:Cannot use import statement outside a module

NestJS 集成 Hardhat HRE 部署合约的模块冲突解决方案

问题根源

你的项目同时使用了NestJS的CommonJS模块配置与Hardhat的TypeScript生态,模块系统混用导致了require插件失效、import语句报错的冲突。以下是针对性的解决步骤:


1. 统一Hardhat配置文件的模块格式

将hardhat.config.js(或你当前命名的hardhat.config.ts)改为标准TypeScript格式,用import替代require,确保插件被正确加载:

import 'hardhat-deploy';
import 'hardhat-deploy-ethers';
import '@nomicfoundation/hardhat-toolbox';
import '@nomiclabs/hardhat-ethers';
import dotenv from 'dotenv';

dotenv.config();

export default {
  solidity: '0.8.15',
  // 补充你的网络配置
  paths: {
    sources: 'tokens'
  }
};

2. 调整tsconfig.json适配Hardhat

修改配置文件,确保覆盖Hardhat相关的TypeScript文件,避免模块解析冲突:

{
  "compilerOptions": {
    "module": "CommonJS",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  },
  "include": ["src/**/*.ts", "hardhat.config.ts", "deploy/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

3. 编写规范的部署脚本

在项目根目录创建deploy文件夹,放置TypeScript格式的部署脚本(如deploy/deploy-token.ts),利用Hardhat的TypeScript运行时处理模块:

import { ethers } from 'hardhat';

async function main() {
  const tokenFactory = await ethers.getContractFactory('Token');
  const token = await tokenFactory.deploy(); // 替换为你的部署参数args
  await token.deployed();
  console.log(`Token合约部署地址:${token.address}`);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

4. 配置部署脚本命令

在package.json中添加Hardhat运行命令,直接调用编译后的TypeScript脚本:

{
  "scripts": {
    "deploy": "hardhat run deploy/deploy-token.ts --network 你的网络名称"
  }
}

问题解释

  • require插件失效:你的hardhat.config.ts使用了CommonJS的require语法,但文件名是.ts,导致Hardhat的TypeScript插件无法正确识别和加载依赖。
  • import语句报错:tsconfig配置为CommonJS模块系统,未经编译的import语句直接运行时,Node.js会按CommonJS规则处理,从而抛出"Cannot use import statement outside a module"错误。

内容的提问来源于stack exchange,提问作者Akshit Soneji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:25:39