Search code examples
socketssocket.iopolymerweb-component

How to import socket.io.client javascript in polymer 3 PWA starter kit app for server build


I am using a socket.io-client connection in my web component and need to import the socket.io-client java library (socket.io-client github).

Usage in web-component: var socket =  io.connect(socket_url);

All ways to import the socket.io-client.js fail with using different import variants like the one below directly in my web component:

import io from 'socket.io-client'

I searched and found (solution) that socket.io-client provides no ES modules which polymer requires for import. The proposed solution taken from this answer suggests to include the socket.io javascript directly in the main index.html. So I am now importing the socket.io-client script in my index.html with

<script src="node_modules/socket.io-client/dist/socket.io.slim.js" crossorigin></script>

This solution works in development and testing with:

npm start

The build works and the application and socket implementation is working as expected at http://127.0.0.1:8081 in the browser.

But when I start the build process for production and serve with:

npm run build:prpl-server
npm run serve:prpl-server
...
prpl-server listening http://127.0.0.1:8080

The build is successful but the application fails to run in browser with the following error in the console:

Loading failed for the with source “http://127.0.0.1:8080/es6-bundled/node_assets/socket.io-client/dist/socket.io.slim.js”.

So the socket.io...js file is not put/copied into the build folders during the build process. There is even no node_assets folder in the build directory. However the code and testing works - so the import and script seems to work correctly. I am doing something wrong for the final build but dont understand what.

So the question is how to correctly import the socket.io-client javascript in the index.html or web component to correctly output it into the final build?


Solution

  • I think you need to add "node_modules/socket.io-client/dist/**" to the extraDependencies part of the polymer.json in order for the build process to take the files in account

    It would look something like this

    {
      "extraDependencies": [
        "manifest.json",
        "node_modules/@webcomponents/webcomponentsjs/**",
        "push-manifest.json",
        "node_modules/socket.io-client/dist/**"
      ]
    }