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

Node.js使用ECMA规范导入其他文件函数报SyntaxError错误如何解决

问题原因及解决方案

核心错误原因

Node.js 没有将你的app.js识别为ECMA模块,而是按CommonJS规范解析,CommonJS不支持import语法,因此解析到import后的{时直接抛出语法错误。

具体排查及解决步骤

  • 检查Node.js版本
    执行node -v查看当前版本,ECMA模块的稳定支持需要Node.js版本 >= v12.20.0 或 >= v14.13.0,版本过低请升级到Node.js长期支持版本即可。
  • 确认执行命令的目录正确
    必须在package.json所在的项目根目录下执行启动命令node app.js,如果在子目录执行,Node.js无法读取到package.json中"type": "module"的配置,会默认将.js文件识别为CommonJS模块。
  • 低版本兼容方案(不需要升级Node.js的情况)
    将app.js的后缀修改为.mjs,Node.js所有支持ESM的版本都会默认将.mjs文件识别为ECMA模块,不需要依赖package.json的配置。
    如果仍想用CommonJS规范,将代码改为以下写法即可:
    app.js修改为:
    const {showUsers, callUserProfile} = require("./callModule.mjs");
    
    showUsers();
    callUserProfile();
    
    callModule.mjs的导出语法也改为CommonJS写法:
    function showUsers(){
        console.log("this is show users function");
    }
    
    function callUserProfile(){
        console.log("This is user profile function");
    }
    
    module.exports = {showUsers, callUserProfile}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:09:03