node.js:使用 es6 导入 socket.io

Dig*_*yay 10 node.js socket.io ecmascript-6

我正在编写一个示例代码来使用 es6 脚本处理 node.js 中的套接字连接,在导入 socket.io 时会引发错误

import {
  PORT
} from './config';

import express from 'express';
import io from 'socket.io';

var app = express();

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
  res.send('hello world')
});

io.on('connection', function(socket) {
  console.log('a user connected');
});

app.listen(PORT, () => console.log(`Example app listening on port ${PORT}!`));
Run Code Online (Sandbox Code Playgroud)

错误是

/index.js:17 _socket.default.on('connection', function (socket) { ^

TypeError: _socket.default.on 不是 Object.on (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/src/index.js:15:4) at Module._compile (module.js:643:30) 的函数在 Module._compile (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/node_modules/pirates/lib/index.js:83:24) 在 Module._extensions..js (module.js:654:10) 在 Object.newLoader [as .js] (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/node_modules/pirates/lib/index.js:88:7) at Module.load (module.js:556:32) at tryModuleLoad (module.js) :499:12) 在 Function.Module._load (module.js:491:3) 在 Function.Module.runMain (module.js:684:10) 在 Object。(/Users/digvijay.upadhyay/digvijayu/websocket_with_node/node_modules/@babel/node/lib/_babel-node.js:224: 23) [nodemon] 应用程序崩溃 - 在启动之前等待文件更改... 使用 Babel 成功编译了 2 个文件。使用 Babel 成功编译了 2 个文件。

mat*_*mik -8

您需要调用函数require('socket.io')()并向那里传递一个快速实例。

请查看添加的代码示例:

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();
const server = http.createServer(app);
// this line \/
const io = socketIO(server);
// this line /\


io.on('connection', (socket) => {
    //...
});

server.listen(port, () => {
    //...
});
Run Code Online (Sandbox Code Playgroud)

  • 我已经阅读了使用 `require` 的解决方案,但我想知道是否可以使用 es6 `import` 进行导入 (5认同)
  • OP 使用 ECMAScript 模块编写其代码片段。您提供的解决方案是使用 CommonJS 编写的。您不仅没有回答问题,而且甚至没有开始使用OP提供的代码。你回答什么问题? (3认同)