node express template typescript in javascript

To create a Node.js Express web application with TypeScript, you need to follow these steps:

  1. Initialize the project with NPM: npm init -y
  2. Install the required dependencies: npm install express typescript ts-node @types/express --save-dev
  3. Create a tsconfig.json file with the following contents:
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "./dist",
    "esModuleInterop": true
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}
227 chars
16 lines
  1. Create a src folder and a server.ts file inside it with the following contents:
index.ts
import express, { Request, Response } from 'express';

const app = express();

app.set('view engine', 'ejs');
app.set('views', './views');

app.get('/', (req: Request, res: Response) => {
  res.render('index', { title: 'Express with TypeScript' });
});

app.listen(3000, () => {
  console.log('The application is listening on port 3000!');
});
344 chars
15 lines
  1. Create a views folder inside the project root with an index.ejs file that looks like this:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title><%= title %></title>
  </head>
  <body>
    <h1><%= title %></h1>
  </body>
</html>
154 chars
11 lines
  1. Add a script to the package.json file that will build and run the application:
{
  "scripts": {
    "start": "ts-node ./src/server.ts" 
  }
}
63 chars
6 lines
  1. Run the application with the command: npm start

This will start the application on port 3000 and render the index.ejs view with the title 'Express with TypeScript'.

gistlibby LogSnag