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"] }
我曾把路径别名@/改为@@/,但问题仍未解决。
解决方法
修改tsconfig的模块配置
把tsconfig中compilerOptions里的"module": "esnext"改为"module": "commonjs"。因为Hardhat运行在Node.js环境,默认采用CommonJS模块规范,ESNext模块会导致import语句无法被正确解析。为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";
- 检查导入语法
确保hardhat.config.ts及相关脚本中的导入语法符合CommonJS规范,或通过上述tsconfig配置让TypeScript正确转译ES模块语法。
内容的提问来源于stack exchange,提问作者Shivam Sahil
相关产品推荐
相关产品推荐

