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

将JS转为MJS模块后,如何从Shell脚本调用其函数?

解决Node.js中通过--eval调用ES模块(.mjs)函数的问题

问题根源

node --eval默认以CommonJS模块模式执行代码,即便加上--experimental-modules,也不会将eval内容识别为ES模块,因此import语句无法生效。另外报错里的foo.bar(, )说明你的$a或$b变量为空,导致语法不合法,这也是需要修正的点。

解决方案

要在--eval中使用ES模块语法,需添加--input-type=module参数,同时保证参数传递的语法正确性:

1. 基础命令修正

使用以下格式调用bar函数:

node --input-type=module --eval "import foo from './foo.mjs'; foo.bar(${a:-undefined}, ${b:-undefined})"
  • --input-type=module:告知Node.js将eval代码当作ES模块处理,让import语句正常生效。
  • ${a:-undefined}/${b:-undefined}:避免变量为空时出现foo.bar(, )这类语法错误,变量为空时自动填充undefined。

2. 字符串参数处理

如果$a、$b是字符串类型,需要给参数加引号,防止Shell解析出错:

node --input-type=module --eval "import foo from './foo.mjs'; foo.bar('${a:-}', '${b:-}')"

3. 测试示例

假设你的foo.mjs内容如下:

export default {
  bar: (x, y) => {
    console.log(`参数:${x}, ${y}`);
  }
};

执行命令(设置a=hello、b=world):

a=hello b=world node --input-type=module --eval "import foo from './foo.mjs'; foo.bar('${a:-}', '${b:-}')"

会正常输出:参数:hello, world

额外说明

  • Node.js v14及以上版本中ES模块已是稳定特性,无需再添加--experimental-modules参数。
  • 直接运行node foo.mjs能正常执行,是因为.mjs文件会被自动识别为ES模块,而--eval需要显式指定模块类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:01:07