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

React Native引入自定义npm库报错:TypeError: undefined is not a function

React Native引入自定义npm库时出现TypeError与类型声明缺失问题的排查与解决

问题成因

  • 导出方式不匹配:你开发的mobile-number-validator库可能使用了默认导出,但项目代码中采用了命名导入的方式,导致isValidPhoneNumber变量实际为undefined,调用时触发「TypeError: undefined is not a function」错误。
  • 缺少TypeScript类型声明:该npm库未提供对应的.d.ts类型声明文件,而React Native/Expo项目默认启用了类型检查机制,因此出现「Could not find a declaration file for module」的提示。

可行解决方法

修复导出方式不匹配问题

  1. 调整项目导入方式适配默认导出
    如果你的库源码是默认导出(比如module.exports = isValidPhoneNumber或export default isValidPhoneNumber),将项目中的导入代码修改为:

    import isValidPhoneNumber from 'mobile-number-validator';
    
  2. 修改npm库的导出方式为命名导出
    若你有权限修改自定义库的代码,将导出逻辑改为命名导出,确保和项目导入方式一致:

    // 库的核心源码文件
    export function isValidPhoneNumber(phoneNumber) {
      // 你的手机号验证逻辑
    }
    // 若使用CommonJS规范
    module.exports.isValidPhoneNumber = isValidPhoneNumber;
    

    修改完成后重新发布npm包,再在项目中执行npm update mobile-number-validator更新依赖。

修复类型声明缺失问题

  1. 手动添加本地类型声明文件
    在项目根目录创建typings/mobile-number-validator/index.d.ts文件,写入以下内容:

    declare module 'mobile-number-validator' {
      export function isValidPhoneNumber(phoneNumber: string): boolean;
    }
    

    接着在项目的tsconfig.json(TypeScript项目)或jsconfig.json中配置类型声明路径:

    {
      "compilerOptions": {
        "typeRoots": ["./typings", "./node_modules/@types"]
      }
    }
    
  2. 临时忽略类型检查
    若不需要严格的类型校验,可在导入语句前添加注释跳过类型检查:

    // @ts-ignore
    import { isValidPhoneNumber } from 'mobile-number-validator';
    

额外排查步骤

  • 清理依赖缓存:执行npm cache clean --force,删除node_modules和package-lock.json后重新执行npm install
  • 清除Metro缓存重启服务:执行npx expo start -c以清除缓存的方式启动Metro服务器,避免缓存导致的模块加载异常

内容的提问来源于stack exchange,提问作者Taha Yasin Erel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:12:55