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

Hardhat执行npx hardhat node报错:Cannot use import statement outside a module

问题:执行npx hardhat node时报错SyntaxError: Cannot use import statement outside a module

我的项目文件夹结构如下:

  • hardhat.config.ts
  • src
    • scripts
    • contracts
    • ...

执行命令npx hardhat node时,出现错误:SyntaxError: Cannot use import statement outside a module

当前的tsconfig配置:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "baseUrl": ".",
    "paths": {
      "@@/*": ["./src/*"],
      "@@/components/*": ["./src/app/components/*"]
    },
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

我曾把路径别名@/改为@@/,但问题仍未解决。


解决方法

  1. 修改tsconfig的模块配置
    把tsconfig中compilerOptions里的"module": "esnext"改为"module": "commonjs"。因为Hardhat运行在Node.js环境,默认采用CommonJS模块规范,ESNext模块会导致import语句无法被正确解析。

  2. 为Hardhat单独配置tsconfig(推荐)
    当前tsconfig是为Next.js项目配置的(包含next插件、jsx支持等),和Hardhat的运行需求冲突。可以单独创建适用于Hardhat的配置:

  • 在项目根目录新建tsconfig.hardhat.json,内容如下:
{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "baseUrl": ".",
    "paths": {
      "@@/*": ["./src/*"]
    }
  },
  "include": ["hardhat.config.ts", "src/**/*.ts"],
  "exclude": ["node_modules", ".next"]
}
  • 在hardhat.config.ts最顶部添加代码,指定Hardhat使用该配置文件:
process.env.TS_NODE_PROJECT = "./tsconfig.hardhat.json";
  1. 检查导入语法
    确保hardhat.config.ts及相关脚本中的导入语法符合CommonJS规范,或通过上述tsconfig配置让TypeScript正确转译ES模块语法。

内容的提问来源于stack exchange,提问作者Shivam Sahil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:45:05