Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ESM import: Schema is not a constructor #312

Open
scjmjy opened this issue Jun 12, 2022 · 5 comments
Open

ESM import: Schema is not a constructor #312

scjmjy opened this issue Jun 12, 2022 · 5 comments

Comments

@scjmjy
Copy link

scjmjy commented Jun 12, 2022

我有一个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

@mouday
Copy link

mouday commented Jun 28, 2022

我也遇到这个问题了

@mouday
Copy link

mouday commented Jun 28, 2022

可以不改源码

import asyncValidator from 'async-validator';

const Schema = asyncValidator.default;

@JE-lee
Copy link

JE-lee commented Dec 4, 2022

同样的问题

@theruziev
Copy link

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

@JE-lee
Copy link

JE-lee commented Dec 5, 2022

同样的问题

主要是因为 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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants