问题
I'm currently working on a project in polymer 3, one of the components needs to import socket.io-client but whatever i try i can't get it to work.
I have tried:
import io from 'socket.io-client';
what i get back:
Uncaught SyntaxError: The requested module '../../node_modules/socket.io-client/lib/index.js' does not provide an export named 'default'
same for this:
import io from 'socket.io-client/dist/socket.io.js';
what i get back:
Uncaught SyntaxError: The requested module '../../node_modules/socket.io-client/dist/socket.io.js' does not provide an export named 'default'
I have also tried this:
import * as io from 'socket.io-client'
what i get back:
ReferenceError: require is not defined at index.js:4
and this:
import * as io from 'socket.io-client/dist/socket.io.js'
what i get back:
TypeError: Cannot read property 'Buffer' of undefined
I later on looked trough the code from socket.io-client and there really don't appear to be any es6 exports used in the code, that would explain why it indeed doesn't work.
What i find weird tho is that the import syntax is even listed on their site as supported. I assume i may be using a wrong build or something but i don't know why that would be true as i use "socket.io-client": "^2.1.1"
if anyone knows what i'm doing wrong i'd be happy to hear.
回答1:
Polymer requires the use of ES modules - since socket.io-client fails to have module in package.json (https://github.com/rollup/rollup/wiki/pkg.module), Polymer must rely on a source which is written with ES modules. Socket.io-client provides neither. So you could only import it in index.html or one of your templates or use another library (or do some crazy thing with webpack / gulp)...
index.html
<script src="node_modules/socket.io-client/dist/socket.io.js"></script>
I have imported it after webcomponents import.
In a component:
const socket = io(...);
works.
回答2:
Inspecting the socket-io-client they have this so-called "UniversalModuleDefinition" that runs when the script is imported, you can see it here:
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["io"] = factory();
else
root["io"] = factory();
})(this, function() {
... //does io setup factory presumably
}
The problem
If we try to import using import './socket.io.js'
, (i.e. we just are using vanilla js and we are not using webpack, amd, or requirejs) then root
is undefined.
One solution
Modify socket-io client js to check for this undefined root and set it to the window, like so:
if(root === undefined){
root = window;
}
root["io"] = factory();
Then you can simply do import './socket.io.js'
and you will have io()
in global scope.
来源:https://stackoverflow.com/questions/52310242/socket-io-client-no-default-export