0

I've been trying to port my app from older Svelte3/Rollup to newer Vite based setup and am having trouble initializing sails.io.js client to work inside Svelte.
What used to work really well in the past with Svelte3/Rollup was:

Inside /public/index.html (after manually placing sails.io.js into /public/libs:

<script src="/libs/sails.io.js" autoConnect="false"></script>

Inside /src/global-state.js (my global persistent vars):

export var mySocket;
import io from 'io';    // this 'io' global would resolve fine!
io.sails.url = 'http://localhost:1337';
mySocket = io.sails.connect();

Then it was just a matter of importing mySocket variable into any svelte component.

But with newer Svelte/Vite versions this approach doesn't work anymore.
Obviously I now place sails.io.js inside /static/libs and it is located fine by <script> tag in the HTML.
Then calling import io from 'io' gives me a Cannot find module 'io' imported from '....../src/global-state.js' error, which is the heart of my question!

What I've tried, and none of which worked was:

  • Installing npm install sails.io.js, then doing import io from 'sails.io.js'; which imports but gives me an undefined object with which I can do nothing useful...
  • As a continuation of the above, trying to deal with the io object inside onMount() function, which still resolves to undefined.
  • Trying to force a global alias inside vite.config.js as per this workaround. Gives a bunch of errors.

I would really appreciate any clues as to how to proceed! Thank you!

Eximorp
  • 331
  • 4
  • 11

1 Answers1

1

No promises beacuse I've never used sails before, but try this out:

First install both sails.io.js and socket.io-client via NPM.

npm install socket.io-client --save
npm install sails.io.js --save

Then, in global-state.js, use the below code to set up the client:

import socketIOClient from 'socket.io-client';
import sailsIOClient from 'sails.io.js';

const io = sailsIOClient(socketIOClient);

io.sails.url = 'http://localhost:1337';

export const mySocket = io.sails.connect();

You shouldn't need <script src="/libs/sails.io.js" /> or anything in the /public/libs directory

Oscar Hermoso
  • 302
  • 2
  • 12
  • 1
    Thank you very much! This worked 90%, it got me to the point where the client initialized but now wouldn't connect to Sails.js server. After digging deeper I've discovered that `sails.io.js` only works with `socket.io-client` version 2.0.3, as per [here](https://github.com/0xGREG/sails-ub-poc/pull/1). So if you could edit the first line of your answer code to be `npm install socket.io-client@2.0.3 --save --save-exact` this would complete the answer. Thanks again! – Eximorp Jul 23 '23 at 16:20