yiminghe / async-validator

validate form asynchronous

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ESM import: Schema is not a constructor

scjmjy opened this issue · comments

我有一个ESM的项目(不是vue前端这样的项目,而是 express 后端项目,使用了 ESM 模块),
引用了 async-validator,如下:

import Schema from "async-validator";
const schema = new Schema(xxxx);

上面的代码会报错:TypeError: Schema is not a constructor

如果对 async-validator/dist-node/index.js 最后一行代码进行如下修改,则问题修复:

// exports['default'] = Schema; // 注释掉原本的代码
module.exports = Schema; // 改用这一行,问题解决

希望修改一下源码以支持 ESM

我也遇到这个问题了

可以不改源码

import asyncValidator from 'async-validator';

const Schema = asyncValidator.default;

同样的问题

the same issue, async-validator doesn't work for node environment

同样的问题

主要是因为 node 原生的 ESM 规范并不支持 __esModule 这个约定。解决的方法可以参考这个库 node-cjs-interop

export function interopImportCJSDefault<T>(d: T): T {
  return d && (d as DefaultWrapper<T>).__esModule
    ? (d as DefaultWrapper<T>).default
    : d;
}

type DefaultWrapper<T> = T & { default: T; __esModule?: boolean };

import AsyncValidator from 'async-validator'
const ValidateSchema = interopImportCJSDefault(AsyncValidator)