bellotas
bellotas

Reputation: 2461

How to use libraries which have been required by RequireJS

I have tried to import MQTT using REQUIREJS but I am getting an error:

Uncaught ReferenceError: mqtt is not defined

The code I am trying to run is in an HTML file:

HTML

    <script>
    require(["https://unpkg.com/[email protected]/dist/mqtt.min.js"], function (mqtt) {
        console.log("Libraries loaded");
    })
</script>
<script src="../text-to-speech/sub_mqtt.js"></script>

sub_mqtt

    //MQTT Connection
function mqtt_connect() {
    //var mqtt = require('mqtt'); // Should I use it?
    var client = mqtt.connect({ host: 'test', port: port })
    var topic = 'mytopic'

    client.on('message', (topic, message) => {
    });


    client.on('connect', () => {
        client.subscribe(topic);
        console.log("Connected!")
    });
};

mqtt_connect();

I know that if I copy this code into the first script call back, I would solve the error, but I would like to do it in a different file to avoid overcrowding the HTML.

Upvotes: 0

Views: 236

Answers (1)

Damian Dziaduch
Damian Dziaduch

Reputation: 2127

RequireJS is async module loader, so your method of loading is wrong because you have no guarantee that mqtt will be loaded before your script.

To make sure that your code will be executed after mqtt load, you have to pass it as callback to RequireJS. First, amend your HTML code to:

<script src="../text-to-speech/sub_mqtt.js"></script>

Then edit your sub_mqtt script and make sure that your code is a callback to RequireJS:

require(['https://unpkg.com/[email protected]/dist/mqtt.min.js'], function (mqtt) {
    var client = mqtt.connect({ host: 'test', port: port })
    var topic = 'mytopic'

    client.on('message', (topic, message) => {
    });


    client.on('connect', () => {
        client.subscribe(topic);
        console.log("Connected!")
    });
});

Upvotes: 1

Related Questions