ESM 模块的快速验证器用法

express-validator usage with ESM modules

我尝试在 Node.js v8.7.0 中使用 --experimental-modules 标志使用此语法导入 ESM 模块:

import { check, validationResult } from 'express-validator/check';
import { matchedData, sanitize } from 'express-validator/filter';

但是我收到以下错误:

(node:29028) ExperimentalWarning: The ESM module loader is experimental.
SyntaxError: The requested module does not provide an export named 'check'
    at checkComplete (internal/loader/ModuleJob.js:86:27)
    at moduleJob.linked.then (internal/loader/ModuleJob.js:69:11)
    at <anonymous>

使用 --experimental-modules 标志打开 ESM 模块的正确用法是什么?

我也用 @std/esm 包测试过。它只适用于我转 cjs: true.

发生这种情况是因为,在 Node.js 中,通过 import 导入的 CommonJS 模块只有默认导出*。

如果您要导入的模块不是 ES 模块(express-validator 就是这种情况),那么您所能做的就是这样:

import checkAPIs from 'express-validator/check';
import filterAPIs from 'express-validator/filter';

const { check, validationResult } = checkAPIs;
const { matchedData } = filterAPIs;

* 来源:https://medium.com/the-node-js-collection/an-update-on-es6-modules-in-node-js-42c958b890c

现在,当做 from 'express-validator/check' 时,它说,requires to express-validator/check are deprecated.You should just use require("express-validator") instead. 具有讽刺意味的是,CommonJS 模块在某种程度上也是如此。

import validator from 'express-validator'
const { body } = validator

使用这个...

import validator from 'express-validator'
const { check, validationResult } = validator