Skip to content

Build the Client using TSC

Video Lecture

Build the Client using TSC Build the Client using TSC

Description

In this lesson, I show how to use TSC in watch mode, to create the ./dist/client.js script from the client TypeScript source code.

Note that this version will use an importmap to tell the browser where it can find the socket.io-client when it encounters it in the ES6 import statement present in the transpiled client.js.

Update ./dist/client/index.html with this code.

./dist/client/index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>
      Socket.IO TypeScript Tutorials by Sean Bradley : https://sbcode.net/tssock/
    </title>
    <style>
      body {
        font-size: 4vw;
      }
    </style>
    <script type="importmap">
      {
        "imports": {
          "socket.io-client": "/socket.io/socket.io.esm.min.js"
        }
      }
    </script>
  </head>

  <body>
    <script type="module" src="client.js"></script>
  </body>
</html>

Create a client.ts file in the folder ./src/client/

./src/client/client.ts

1
2
3
4
5
6
7
import { io } from 'socket.io-client'

const socket = io()

socket.on('connect', () => {
  document.body.innerText = 'connected : ' + socket.id
})

Install the socket.io-client dependency.

npm install socket.io-client --save-dev

Create a tsconfig.json file in the ./src/client/ folder.

./src/client/tsconfig.json

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

Update the ./package.json scripts option with,

1
2
3
  "scripts": {
    "dev" : "concurrently -k \"tsc -p ./src/server -w\" \"nodemon ./dist/server/server.js\" \"tsc -p ./src/client -w\""
  },

And then we can start, by typing the command,

npm run dev

Visit http://127.0.0.1:3000