📦不能使用 import 语句(模块设置)
SyntaxError: Cannot use import statement outside a module
文件用的是 “import” 这种新写法(ES 模块),但运行环境却按旧写法(require)来读取。
🤔 为什么会出现?
- package.json 里没有 "type": "module" 设置
- 旧写法和新写法的文件混在一起了
- 文件扩展名(.js/.mjs/.cjs)和设置不匹配
🔧 试试这样做
- 确定项目用哪种写法,并统一成一种
- 把 package.json 和报错一起给 AI 看,会更快
🤖 这样问 AI
出现了下面的 'Cannot use import statement outside a module' 报错。请检查 package.json 设置和文件扩展名,把模块写法统一成一种。 [在这里粘贴完整的报错]
把 [ ] 部分换成你的实际情况,报错前后的几行也尽量一起复制粘贴。
相关术语
同一分类的其他报错
- 找不到模块
Module not found: Can't resolve - 找不到命令
command not found - 包版本冲突(ERESOLVE)
npm ERR! ERESOLVE unable to resolve dependency tree - 端口已被占用
EADDRINUSE: address already in use - 类型不匹配(TypeScript)
Type 'X' is not assignable to type 'Y' - 没有权限,安装不了(EACCES)
EACCES: permission denied - Node 版本不匹配
The engine "node" is incompatible with this module - 内存不足(heap out of memory)
JavaScript heap out of memory - 代码检查(ESLint)没通过,构建失败
Failed to compile — ESLint errors - 找不到文件或文件夹(ENOENT)
ENOENT: no such file or directory