I am currently diving into socket.io for my upcoming Vue project, but I seem to be encountering some issues. Interestingly, everything works smoothly when I use vue-cli, however, I prefer working with Vite.js due to its speed and customization options. Unfortunately, when I attempt to integrate socket.io with vite, I keep seeing it disconnected in the console. It seems there might be a conflict between esbuild and commonjs. I even tried using vite-plugin-commonjs to support commonjs modules but ran into the same issue.
I've copied and pasted my code from vue-cli to Vite, where it works flawlessly in vue-cli but remains disconnected in Vite.
This is my server-side code:
const express = require("express");
const socket = require("socket.io");
const app = express();
const server = app.listen(3001, function () {
console.log("server running on port 3001");
});
const io = socket(server, {
cors: {
origin: "*",
},
});
io.on("connection", function (socket) {
console.log(socket.id);
socket.on("SEND_MESSAGE", function (data) {
io.emit("MESSAGE", data);
});
});
This is my frontend (Vue) code:
<template>
<button @click="echo">Echo</button>
</template>
<script>
import { io } from "socket.io-client";
export default {
data() {
return {
socket: io("http://localhost:3001"),
};
},
methods: {
echo() {
console.log(this.socket.disconnected);
},
},
};
</script>
Thank you in advance for any assistance!