【问题标题】:Convert nodejs server to ES6 syntax将 nodejs 服务器转换为 ES6 语法
【发布时间】:2018-03-02 21:37:25
【问题描述】:

我的 nodejs 服务器是这样的:

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

const port = process.env.PORT || 8000;

// Routes ===============================================
require('./routes.js')(app);

// Socket.io ============================================
require('./socket.js')(io);

// Launch ===============================================
http.listen(port, function() {
    console.log('The magic happens on port '+port);
});

我想把它改成 ES6 语法,但我不知道该怎么做:

import express  = 'express';
import http = 'http';
import io = 'socket.io';
import routes './routes';
import sockets './sockets';

const port = process.env.PORT || 8000;

// Routes ===============================================
routes(express);

// Socket.io ============================================
sockets(io);

// Launch ===============================================
http.listen(port, function() {
    console.log('The magic happens on port '+port);
});

但它不起作用。

【问题讨论】:

  • 更新你的 node.js 到最新版本?
  • 导入它们,然后使用所述参数调用它们。混乱在哪里?您已经证明您知道如何以import express 举例说明。
  • 这里有什么问题?
  • @jfriend00 如何将该代码转换为 ES6 语法?
  • 下次,请在您的问题中准确说明您所做和不知道的事情,以便我们确切知道您要问什么。我们不知道您为什么认为 http 示例与 express 示例有任何不同。

标签: javascript node.js ecmascript-6


【解决方案1】:
import express from 'express';
import http from 'http';
import socketIo from 'socket.io';

import routes from './routes';
import sockets from './sockets';

const app = express();
const server = http.Server(app);
const io = socketIo(server);

app.use(routes);
const mySockets = sockets(io);

【讨论】:

  • require('./routes.js')(app);要求('./socket.js')(io);
  • 对于路由,从 ./'routes' 导入路由; app.use(路线)。不知道你对 socket.js 的意思是什么。你能再解释一下吗?
  • 我在另一个 js 文件中只有我所有 socket.io 的 module.exports
  • 我将从 './sockets' 导入套接字; const mySockets = sockets(io);
  • @Tibebes.M 是有道理的。我在命名方面很糟糕,这是一个我没有考虑过 var 命名的原型。我现在改了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
相关资源
最近更新 更多