Search code examples
javascriptnode.jsexpressnode-modulesexpress-validator

express-validator usage with ESM modules


I tried to import into an ESM module with this syntax in Node.js v8.7.0 with --experimental-modules flag:

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

However I'm getting the following error:

(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>

What is the correct usage with ESM modules turned on with --experimental-modules flag?

I tested with @std/esm package also. It only works of I turn cjs: true.


Solution

  • This happens because, in Node.js, CommonJS modules imported via import only have a default export*.

    If the module you're importing is not an ES Module (which is the case of express-validator), then all you can do is something like this:

    import checkAPIs from 'express-validator/check';
    import filterAPIs from 'express-validator/filter';
    
    const { check, validationResult } = checkAPIs;
    const { matchedData } = filterAPIs;
    

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