I'm using Typescript and webpack.
I installed the mqtt.js module (https://www.npmjs.com/package/mqtt) following the directions on their npm-page using
npm install mqtt --save
And now I'm trying to use that module.
When I use this module in a Node project everything works fine, but as soon as I try to import it in my webpack project I'm getting following error in the browser console:
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
I already tried different javascript versions in the tsconfig.json and different import styles, but none seems to work. Currently my code looks like this:
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();
Strangely the console.log in line 7 outputs the following:
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
...
which looks to me, like the connect function is loaded, so I don't get, why I can't call it.
As I said, I already tried different import styles like
import {connect} from "../node_modules/mqtt";
or
import {connect} from "mqtt";
, but that barely changes anything.
My tsconfig.json looks like this
{
"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
}
}
and in the package.json I have following dependencies added
"dependencies": {
"mqtt": "^5.3.0",
"webpack": "^5.89.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
}
PS: If I change the "module" in tsconfig.json from es6 to commonjs, the error changes to the following
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
Okay, that's a bit embarassing, but like one minute after my question I found a solution. Using my original aproach with
I have to call the functions like
I honestly have no explanation to this, I think this may be because the functions get exported as default in this module, but I'm new to this. I'll mark this as solved, but if you have an explanation, I'd be happy to read it.