Spongi
Spongi

Reputation: 549

Webpack polyfills for React application using MQTT

I created a new project using a typescript template using create-react-app. I want my react app to subscribe to MQTT Broker. That's why I used the typescript mqtt library. I followed the documentation, but after starting my react app I become the following problem:

ERROR in ./node_modules/mqtt/lib/connect/index.js 5:12-26
Module not found: Error: Can't resolve 'url' in '/Users/test/Code/mqtt-subscriber/node_modules/mqtt/lib/connect'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "url": require.resolve("url/") }'
    - install 'url'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "url": false }

The used versions are:

    "mqtt": "^4.3.7",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",

Do you have any ideas on how to resolve the problem? I don't have a webpack configuration file.

If I install the url package I get other error:

Buffer is not defined 'url'5:12-26 Module not found

Upvotes: 1

Views: 314

Answers (2)

Ibtehaj Khan
Ibtehaj Khan

Reputation: 39

Heavily borrowing from @Taxel's answer, you have to use:

import * as mqtt from 'mqtt/dist/mqtt.min';

As mentioned by the maintainers of the library here

Upvotes: 0

Taxel
Taxel

Reputation: 4207

This looks like this github issue - try importing from dist:

import mqtt from "mqtt/dist/mqtt";

or using mqtt-precompiled

Upvotes: 1

Related Questions