javascriptnode.jses6-promisees6-moduleses6-module-loader

Imported CommonJS (CJS) into ES Module (MJS) leads to "TypeError: module is not a function" error


I'm trying to migrate from CommonJS (.cjs) to ES Modules (.mjs). To do that I replaced:

const bodyParser = require("body-parser");

with

import * as bodyParser from "body-parser";

within the ES Module.

Now, when try to execute the code:

app.use(bodyParser.urlencoded({
    param: val
}));

I get an error:

app.use(bodyParser.urlencoded({

TypeError: bodyParser.urlencoded is not a function

at file:///…/app.mjs:44:20
at ModuleJob.run (internal/modules/esm/module_job.js:110:37)
at async Loader.import (internal/modules/esm/loader.js:176:24)

I googled for this error and most of the answers reference to a need to require the body-parser component. But in my case I do it already with:

import * as bodyParser from "body-parser";

Any idea why do I still get such issue although the module is imported? Can it be due to asynchronous nature of ES Modules imports? Perhaps, should I wait until all imported modules are really imported?


Solution

  • Try using:

    import bodyParser from "body-parser";