How do we import stompjs in a browser? Or something like stompjs?

Viewed 17083

I am trying to follow this Spring tutorial on how to use websockets. I am using webpack to bundle my code and babel to convert it from ES6. I am trying to pull in sockjs with a normal import statement.

import SockJS from 'sockjs'

But when webpack runs, I get missing module errors,

ERROR in ./~/stompjs/lib/stomp-node.js
Module not found: Error: Cannot resolve module 'net' in /Users/name/Developer/cubs-stack-4/cubs-webapp/node_modules/stompjs/lib
 @ ./~/stompjs/lib/stomp-node.js 14:8-22

ERROR in ./~/websocket/package.json
Module parse failed: /Users/name/Developer/cubs-stack-4/cubs-webapp/node_modules/websocket/package.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "_args": [
|     [
|       "websocket@latest",
 @ ./~/websocket/lib/version.js 1:17-43

mainly because it is expecting to be run on Node.

I have 2 questions.

First, how do I get stompjs into my browser side code using an import/require statement?

Second, how come in the tutorial, they can drop stompjs in the HEAD and it doesn't blow up in the browser, but it does when I run the "same" code through webpack?

5 Answers

installing 'net' dependency solved my issue

npm i sockjs-client --save
npm i stompjs --save
npm i net

and import like this

import * as SockJS from 'sockjs-client';
import * as Stomp from 'stompjs';

In ionic 6 Angular 12

  1. Install

    npm i --save sockjs-client stompjs net

  2. Then

    npm i --save-dev @types/sockjs-client @types.stompjs

  3. Import using

import * as SockJS from 'sockjs-client'; import * as Stomp from 'stompjs';

  1. To solve the issue with 'global' I had to add the following to index.html

    <script type="application/javascript"> var global = window; </script>

Related