Setting up Typescript NodeJS Express - adonisv79/bytecommander.com GitHub Wiki

Note: make sure that you have installed typescript and have added the necessary configurations


Installation

Install the required modules (we are assuming 'typescript' is already installed globally from prev guide)

npm i express body-parser express-session --save
npm i ts-node ts-node @types/node @types/express --save-dev
  • express - the express js framework
  • body-parser- the express payload module
  • express-session - used for handling user sessions
  • ts-node - allows us to run 'ts' files similar to how we run node files. 'node index.js' can be applied to a typescript file for example 'ts-node index.ts'.
  • @types/node - node js types
  • @types/express - expressjs types

Configurations

package.json

update the package.json of the project with the following

{
.
.
.
  "scripts": {
    "dev": "ts-node src/index.ts",
    "prod": "node dist/src/index.js",
    "build": "tsc -p ."
  },
.
.
.
}

this allows you to simply run 'npm run {script-name}'

Testing NodeJS Typescript

If we followed the previous guide mentioned above, we would have an index.ts file in our src folder with the following

// a function to just show hello plus a name
function helloTS(person: string) {
    console.log(`Hello ${person}`);
}

// lets test
helloTS('Adonis L. Villamor');

and also we would have our tsconfig.json look like the following

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "lib": [ "es2015" ],
    "strict": true,
    "declaration": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "esModuleInterop": true,
    "moduleResolution": "node",
    "noImplicitAny": true,
    "outDir": "dist",
    "rootDir": ".",
    "sourceRoot": "src",
    "sourceMap": true
  },
  "include": [ "src/**/*" ],
  "exclude": [
    "node_modules",
    "coverage",
    "**/*.spec.ts"
  ]
}

we can compile this by running 'tsc' so it can generate the proper js file. or exectute the ts file like a regular nodejs file as so

C:\myapp> npm run dev

Express

Now lets set the code to run express. Go to src/index.ts and change the contents to these

import express from 'express'
import path from 'path'

const app = express();
const port = 3000;
const publicPath = path.join(__dirname, '../public')
app.use(express.static(publicPath));

// a function to just show hello plus a name
app.get('/HelloTS', (req, res) => {
    res.send(`Hello ${req.query.person}`)
});

app.listen(port, () => {
    console.log(`Serving static files from ${publicPath}`);
    console.log(`Example app listening on port ${port}!`);
});

create a folder named 'public' in the root where we put in our html files, images etc. Note this is optional and is only needed when serving static files. As a sample, create a new index.html file in the folder and encode the following

<html>
<head>
    <title>Express Cheat Sheet</title>
</head>
<body>
    <div>
        <a href="http://localhost:3000/HelloTS?person=Adonis%20lee%20Villamor">Hello Express</a>
    </div>
</body>
</html>

run the code by executing the following in the terminal

npm run dev

it should now say 'Example app listening on port 3000'. Open your browser and you should see your index.html page. click the link to be redirected to Localhost:3000 HellTS test. You should now see a page saying "Hello Adonis lee Villamor"

⚠️ **GitHub.com Fallback** ⚠️