starting template socket.io typescript node in javascript

To create a template for a socket.io server using TypeScript in Node.js, follow these steps:

  1. Initialize a new Node.js project:
npm init -y
12 chars
2 lines
  1. Install the required dependencies:
npm install --save express socket.io @types/express @types/socket.io typescript ts-node nodemon
96 chars
2 lines
  1. Create a tsconfig.json file with the following content:
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "build",
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}
197 chars
11 lines
  1. Create a src/index.ts file with the following content:
index.ts
import express from 'express';
import http from 'http';
import { Server } from 'socket.io';

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

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

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });

  socket.on('chat message', (msg) => {
    console.log('message: ' + msg);
    io.emit('chat message', msg);
  });
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});
526 chars
25 lines
  1. Add the following scripts to package.json:
{
  "scripts": {
    "start": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts",
    "build": "tsc"
  }
}
118 chars
7 lines
  1. Run the project in development mode with:
npm start
10 chars
2 lines

This will start the server and listen to port 3000. You can test it by opening multiple tabs at http://localhost:3000/ and sending chat messages.

  1. Build and run the project in production mode with:
npm run build
node build/index.js
34 chars
3 lines

This will compile TypeScript into JavaScript and run the server with the compiled code.

gistlibby LogSnag