Issue
I'm using WebSocket for the first time for a project and I keep getting a syntax error from the HTML file that runs the JavaScript file where the bulk of the code is. The relevant code is as follows:
client.js
import WebSocket from 'ws';
const WebSocket = require('ws');
const wss = new WebSocket('wss://example.com');
//rest of code
index.html
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
</head>
<body>
<script type='module' src="./websocket.js"></script>
<script src="client.js"></script>
</body>
</html>
The exact error message I got was "Uncaught SyntaxError: Cannot use import statement outside a module", which originated from the HTML file.
I added the type='module'
part based on an answer to a similar question but I still got the same error message. I believe the cause is to do with how I wrote the WebSocket import in one of the files, potentially which part(s) of the WebSocket library I need to include, but my inexperience with JavaScript is preventing me from identifying a fix.
Solution
You can use WebSocket without import ws module. Web Browser supports WebSocket object as default. I wrote code below.
var ws = new WebSocket("ws://192.168.144.142:8000");
ws.onopen = () => { console.log("WebSocket connected."); };
Answered By - Evan You
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.