如何使用 RequireJS 要求的库

How to use libraries which have been required by RequireJS

我已尝试导入 MQTT using REQUIREJS 但出现错误:

Uncaught ReferenceError: mqtt is not defined

我正在尝试 运行 的代码在 HTML 文件中:

HTML

    <script>
    require(["https://unpkg.com/mqtt@3.0.0/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();

我知道如果我将此代码复制到第一个 script 回调中,我会解决错误,但我想在不同的文件中执行此操作以避免 HTML 过度拥挤.

RequireJS是异步模块加载器,所以你的加载方法是错误的,因为你不能保证mqtt会在你的脚本之前加载。

为确保您的代码将在 mqtt 加载后执行,您必须将其作为回调传递给 RequireJS。首先,将您的 HTML 代码修改为:

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

然后编辑您的 sub_mqtt 脚本并确保您的代码是对 RequireJS 的回调:

require(['https://unpkg.com/mqtt@3.0.0/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!")
    });
});