Here’s how to start express with TypeScript.
Default Package Settings
Create a package.json file.
npm init -y
Install the packages required for express.
yarn add express body-parser
Typescript setting
Install the package for typescript.
yarn add --dev typescript ts-loader ts-node tslint @types/node @types/express
Install necessary information for typescript. And enter the tsconfig.json
file as shown below.
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"moduleResolution": "node"
},
"exclude": [
"node_modules"
]
}
Webpack configuration
yarn add --dev webpack webpack-watch-server
Enter the webpack.config.js
file as shown below.
var path = require('path');
module.exports = {
entry:'./src/index.ts',
target:'node',
output: {
filename:'index.js',
path: path.resolve(__dirname,'dist')
},
devtool:'source-map',
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: ['.ts','.tsx','.js']
},
module: {
rules: [
// all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
{test: /\.tsx?$/, loader:'ts-loader'}
]
}
};
Express Basic Production
Write the src/index.ts
file as shown below.
import * as bodyParser from "body-parser";
import * as express from "express";
import {Request, Response} from "express";
import * as http from'http';
var app:express.Application = express();
app.get('/', (req: Request, res: Response) => {
res.status(200).json({status: "ok"});
});
let httpPort = 3000;
app.set("port", httpPort);
var httpServer = http.createServer(app);
//listen on provided ports
httpServer.listen(httpPort, (data) => {
console.log(`Listening on port ${httpPort}`)
});