使用webpack时调用模块(mqtt)

puruo6ea  于 5个月前  发布在  Webpack
关注(0)|答案(1)|浏览(56)

我使用Typescript和webpack。
我按照npm页面上的说明安装了mqtt.js模块(https://www.npmjs.com/package/mqtt),

npm install mqtt --save

字符串
现在我正试着用那个模块
当我在Node项目中使用此模块时,一切正常,但当我尝试将其导入到webpack项目中时,我在浏览器控制台中遇到以下错误:

Uncaught TypeError: _node_modules_mqtt__WEBPACK_IMPORTED_MODULE_2__.connect is not a function
    at new TestApp (index.ts:23:16)
    at ./src/index.ts (index.ts:40:25)
    at __webpack_require__ (bootstrap:24:1)
    at startup:6:1
    at startup:6:1


我已经尝试了不同的JavaScript版本在tsv.json和不同的导入风格,但似乎没有一个工作。目前我的代码看起来像这样:

mport * as mqtt from "../node_modules/mqtt";

class TestApp
{
    constructor()
    {
        console.log(mqtt);
        
        // start connection to mqtt broker
        let client = mqtt.connect("mqtt://localhost:1883/", {clientId: "ts_client_1", username: "test1", password: "test1", clean: true})
    }
}

(<any>window).TestApp = new TestApp();


奇怪的是,console.log在第7行输出如下:

Module {__esModule: true, Symbol(Symbol.toStringTag): 'Module'}
default
: 
Object
Client
: 
(...)
DefaultMessageIdProvider
: 
(...)
ErrorWithReasonCode
: 
(...)
MqttClient
: 
(...)
ReasonCodes
: 
(...)
Store
: 
(...)
UniqueMessageIdProvider
: 
(...)
applyMixin
: 
(...)
connect
: 
(...)
connectAsync
: 
(...)
default
: 
{Client: ƒ, connect: ƒ, MqttClient: ƒ, Store: ƒ, …}
__esModule
: 
true
...


在我看来,connect函数已经加载了,所以我不明白,为什么我不能调用它。
正如我所说,我已经尝试了不同的导入样式,

import {connect} from "../node_modules/mqtt";


import {connect} from "mqtt";


,但这几乎没有改变任何事情。
我的tslog.json看起来像这样

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "alwaysStrict": true,
        "noImplicitAny": true,
        "noImplicitReturns":true,
        "noImplicitThis": true,
        "module": "es6",
        "target": "es2016",
        "lib": ["es6", "es5", "dom"],
        "moduleResolution": "node",
        "allowJs": false
    }
}


在package.json中,我添加了以下依赖项

"dependencies": {
    "mqtt": "^5.3.0",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1"
  }


PS:如果我将tslog.json中的“模块”从es6更改为commonjs,则错误将更改为以下内容

Uncaught TypeError: (0 , mqtt_1.connect) is not a function
    at new TestApp (index.ts:23:23)
    at ./src/index.ts (index.ts:40:25)
    at __webpack_require__ (bootstrap:24:1)
    at startup:6:1
    at startup:6:1

h6my8fg2

h6my8fg21#

好吧,这有点尴尬,但就在我提出问题的一分钟后,我找到了解决办法。

import * as mqtt from "../node_modules/mqtt";

字符串
我必须调用函数,

mqtt.default.connect(...);


老实说,我对此没有任何解释,我想这可能是因为函数在这个模块中被默认导出,但我是新来的。我将标记为已解决,但如果你有解释,我很乐意阅读它。

相关问题