0

I am having trouble integrating https://www.npmjs.com/package/mqtt into my angular2 typescript project (created with angular-cli).

Using var mqtt = require('mqtt'); produces the error Cannot find name 'require'

Therefore I tried using import (as I normally would) by adding it to the modules.ts:

import { mqtt } from 'mqtt/mqtt';

...
imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    mqtt
],

I tried this with import { MQTT } from 'mqtt/mqtt'; and import { MqttClient } from 'mqtt/mqtt'; as well (the last one is exported as such in the mqtt.js

I even tried importing those in the classfile itself.

I am pretty sure this is a trivial error on my behalf but I cannot get my head around it.

(Note: "@types/node": "^7.0.0", is installed as well, so this won't work either)

my tsconfig:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "isolatedModules": false,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": false,
        "noImplicitAny": false,
        "noImplicitUseStrict": false,
        "removeComments": true,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true
    },
    "exclude": [
        "node_modules",
        "typings/browser",
        "typings/browser.d.ts"
    ],
    "compileOnSave": false,
    "buildOnSave": false,
    "atom": {
        "rewriteTsconfig": false,
        "formatOnSave": true
    }
}
Community
  • 1
  • 1
Wandang
  • 912
  • 2
  • 8
  • 37

2 Answers2

0

The import statement is incorrect; in case you're importing from a generic Javascript module from a Typescript file, you can import all of it - this works with any Javascript library that has some exports:

import * as mqtt from 'mqtt';
let client = mqtt.connnect('mqtt://hostname.example.com'); 

And in case the module was written in Typescript, or has typings that you also have added to your devDependencies in package.json, you could import some of the exported fields:

import { connect } from 'mqtt';
let client = connect('mqtt://hostname.example.com');

In case of this very module, it seems it has typings built in, so you can import specific parts of the module.

In your example, you're actually tring to import an mqtt symbol from the mqtt subfolder of the mqtt module, which probably does not exist and thus fails.

Hope that helps!

0

Read the documentation it has suggested how to use it in ts Documentation

import { connect } from 'mqtt';
const client  = connect('wxs://test.mosquitto.org');
Exterminator
  • 1,221
  • 7
  • 14