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

Node.js报错:SyntaxError: Cannot use import statement outside a module 求解决

解决「SyntaxError: Cannot use import statement outside a module」错误

以下是几种可行的解决方法:

  • 标记文件为ES模块
    在项目根目录的package.json中添加或设置"type": "module"字段,Node.js会将所有.js文件当作ES模块处理:

    {
      "type": "module"
    }
    
  • 改用CommonJS语法
    若不想修改package.json,直接替换为CommonJS的require写法:

    const inquirer = require('inquirer');
    
  • 修改文件扩展名
    将目标文件的扩展名从.js改为.mjs,Node.js会自动识别这类文件为ES模块,无需额外配置package.json。

  • 浏览器环境下配置script标签
    如果是在浏览器中出现该错误,需要在引入脚本的<script>标签上添加type="module"属性:

    <script type="module">
      import inquirer from 'inquirer';
      // 后续业务代码
    </script>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:45:30