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

Node.js导入其他JS文件函数时报错TypeError: fn1 is not a function求助

问题排查与解决方法

常见原因

  • 导出引用被切断:CommonJS 规范中 exports 本质是 module.exports 的引用,如果你的 util.js 中存在直接给 exports 赋值的代码(比如 exports = {}),会切断二者的关联,导致挂载在 exports 上的方法不会被实际导出,最终导入的是默认的空对象,解构出来的 fn1 为 undefined,调用就会抛出类型错误。
  • 模块规范混用:如果你的项目 package.json 中配置了 "type": "module",说明项目默认使用 ES 模块规范,此时你用 CommonJS 的 require、exports 语法会出现兼容问题,导出的内容不符合预期。
  • 拼写/大小写错误:检查导出的方法名、导入的方法名是否存在笔误,大小写是否完全匹配,Windows 系统对文件名大小写不敏感,但 Linux/macOS 系统会区分,也可能导致导出异常。

解决步骤

  1. 先确认导入的内容是否符合预期,在 index.js 中加入打印代码验证:
const util = require('./util.js');
console.log(util); // 查看输出是否包含 fn1、fn2 方法
const {fn1, fn2} = util;
  1. 修复导出写法,优先使用 module.exports 避免引用丢失问题,修改 util.js 代码为:
// 写法1:直接挂载到 module.exports
module.exports.fn1 = () => {
  return "fn1";
}
module.exports.fn2 = () => {
  return "fn2";
}

// 写法2:统一导出对象,更易维护
const fn1 = () => "fn1";
const fn2 = () => "fn2";
module.exports = { fn1, fn2 };
  1. 如果项目使用 ES 模块规范(存在 "type": "module" 配置),统一改用 ES 模块语法:
    util.js 调整为:
export const fn1 = () => "fn1";
export const fn2 = () => "fn2";

index.js 调整为:

import { fn1, fn2 } from './util.js';
const fn0 = () => {
  const ret = fn1();
}
fn0();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:15:01