【问题标题】:Imported CommonJS (CJS) into ES Module (MJS) leads to "TypeError: module is not a function" error将 CommonJS (CJS) 导入 ES Module (MJS) 导致“TypeError: module is not a function”错误
【发布时间】:2020-07-09 01:32:56
【问题描述】:

我正在尝试从 CommonJS (.cjs) 迁移到 ES Modules (.mjs)。为此,我更换了:

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

import * as bodyParser from "body-parser";

在 ES 模块中。

现在,当尝试执行代码时:

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

我收到一个错误:

app.use(bodyParser.urlencoded({

TypeError: bodyParser.urlencoded 不是函数

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)

我搜索了这个错误,大多数答案都提到需要body-parser 组件。但就我而言,我已经这样做了:

import * as bodyParser from "body-parser";

知道为什么在导入模块后我仍然会遇到这样的问题吗?

这可能是由于 ES 模块导入的异步性质造成的吗?
也许,我应该等到所有导入的模块都真正导入了吗?

【问题讨论】:

    标签: javascript node.js es6-promise es6-modules es6-module-loader


    【解决方案1】:

    尝试使用:

    import bodyParser from "body-parser";
    

    【讨论】:

    • 现在我有另一个类似的问题:TypeError: app.use is not a function.
    • 如果您使用express,您还必须以这种方式导入expressimport express from "express";,然后以通常的方式创建app对象(例如:const app = express();)。
    • import * as %module% from %module%import %module% from %module%有区别吗?我以为这只是分配别名的一种方式,不是吗?
    • 导入 CommonJS 模块时必须使用import module from "module";。写在docs
    • 感谢您的链接。有趣的是,对于fs,我使用import * as fs from "fs";,它确实工作,虽然它是一个CJS,据我所知。
    猜你喜欢
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    相关资源
    最近更新 更多