Skip to content

Generate Client JavaScript from TypeScript

Video Lecture

Generate Client JavaScript from TypeScript Generate Client JavaScript from TypeScript

Description

Create client.ts in src/client

1
2
3
4
5
6
7
8
9
class Client {
    private socket: SocketIOClient.Socket

    constructor() {
        this.socket = io()
    }
}

const client = new Client()

Install the Socketio-Client and Types

Note

This code has been updated to support Socket.IO 4.5.1. I had some trouble getting type definitions to work for the client in Socket.IO version 4, so be sure to install the types for version 1.4.36 using the command below. While the version of @types/socket.io-client@1 does not match the Socket.IO 4.5.1, it still works adequate to give the correct intellisense as demonstrated in this course. I will review this need in future updates of Socket.IO.

npm install socket.io-client@4
npm install @types/socket.io-client@1 --save-dev

Note

In the videos i've targeted ES3 and module commonjs for the browser. I also now recommend using the below client tsconfig.json that targets ES6 and ES6 modules.

create tsconfig.json

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{
    "compilerOptions": {
        "target": "ES6",
        "module": "ES6",
        "outDir": "../../dist/client/",
        "baseUrl": ".",
        "paths": {},
        "moduleResolution": "node",
        "strict": true
    },
    "include": ["**/*.ts"]
}

You can manually recompile using

tsc -p ./src/client -w

Or update npm dev script to concurrently generate changes

"dev" : "concurrently -k \"tsc -p ./src/server -w\" \"tsc -p ./src/client -w\" \"nodemon ./dist/server/server.js\"",

Update html to use the new client.js

./dist/client/index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!DOCTYPE html>
<html>
    <head>
        <title>TypeScript Socket.IO Course</title>
    </head>

    <body>
        <script src="socket.io/socket.io.js"></script>
        <script src="client.js"></script>
    </body>
</html>