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

开发Babel插件时使用import语句遇多类报错,求解决方案

解决Babel插件开发中的模块兼容问题

以下是针对你遇到的三个错误的具体解决步骤:

错误1:SyntaxError: Cannot use import statement outside a module

这个错误是因为Node.js默认将.js文件当作CommonJS模块处理,而你的插件代码使用了ES模块的import语法。解决方式是在plugin/package.json中添加"type": "module",明确将该目录下的文件标记为ES模块:

{
  "name": "your-babel-plugin",
  "version": "1.0.0",
  "type": "module"
}

错误2:Error [ERR_UNSUPPORTED_DIR_IMPORT]

添加"type": "module"后,ES模块规范不支持直接导入目录(除非目录配置了exports字段)。你需要在test-plugin/babel.config.json中明确指定插件的完整文件路径,而不是目录路径:

{
  "plugins": ["../plugin/index.js"]
}

错误3:ReferenceError: module is not defined in ES module scope

这个错误说明你的插件代码plugin/index.js中使用了CommonJS的module.exports导出方式,但当前插件已被标记为ES模块,不能混用CommonJS语法。需要将导出语句改为ES模块的export default:

原错误代码(CommonJS):

module.exports = function(babel) {
  return {
    // 插件逻辑
    visitor: {
      // ...
    }
  };
};

修改后(ES模块):

export default function(babel) {
  return {
    visitor: {
      // ...
    }
  };
};

额外注意事项

  • 确保在test-plugin目录下执行Babel命令,路径才会正确解析:
    cd test-plugin
    npx babel test.js
    
  • 如果你的test.js使用ES模块语法,也需要在test-plugin/package.json中添加"type": "module",否则会再次触发Cannot use import statement outside a module错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:45:37