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

JavaScript导入Yup时出现exports未定义错误该如何解决?

问题原因
  • Yup默认发布的是CommonJS格式的模块,使用module.exports/exports语法导出内容,你直接在浏览器原生ES模块环境下引入node_modules中的Yup源码,浏览器无法识别CommonJS语法,因此触发exports is not defined报错。
  • 代码存在大小写不匹配错误:导入时声明的变量是大写Yup,但age字段校验时使用了小写yup,运行时会触发引用错误。
  • validationSchema仅在constructor作用域内定义,后续checkValidity方法无法访问该变量。
解决方案
  1. 修正Yup导入方式
    • 如果你使用Vite/Webpack等构建工具开发,删除路径中的node_modules前缀,直接导入包名即可:import * as Yup from 'yup',构建工具会自动处理CommonJS模块转ES模块、路径解析逻辑。
    • 如果你直接在浏览器使用原生ES模块开发,提前下载适配ES模块的Yup构建产物到本地后引入即可,不要直接加载node_modules目录下的CommonJS格式源码。
  2. 修正语法错误:将age: yup.number()改为age: Yup.number(),和导入的变量名保持大小写一致。
  3. 修正作用域问题:将校验schema挂载到class实例上,方便后续方法调用。
修正后代码示例

EmployeeValidators.js

// 构建工具环境导入写法
import * as Yup from 'yup';

export default class EmployeeValidators {
    constructor(){
        // 将校验规则挂载到实例上,内部方法可通过this访问
        this.validationSchema = Yup.object().shape({
            id: Yup.number().required('Id is required'),
            firstName: Yup.string().required('First name is required'),
            lastName: Yup.string().required('Last name is required'),
            age: Yup.number().required().positive().integer(),
            city: Yup.string().required('City is required')
        });
    }

    checkValidity(employee) {
        return this.validationSchema.isValid(employee);
    }
}

ExampleComponent.js 无需调整,保持原有逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:45:04