How to create an Express.js project with TypeScript


and React.js with TSX

Posted by Pedro Resende on 07/08/2021 10:26

Today I've decided to create an Express.js application with TypeScript and React.js.

To begin our new project, let's start by creating a new express Express.js js project

$ mkdir new-express-js && cd new-express-js
$ npx express-generator --view=react
$ npm i

Now, let's start by adding the necessary packages

$ npm i --save-dev @types/express @types/node @types/react typescript ts-node
$ npm i --save express-react-views react react-dom

let's start by adapting our package.json to use ts-node instead of the default node, to do that you need to update the scripts to

"start": "ts-node ./app.ts"

that way when you run npm run start it will use the ts-node which can interpreter typescript.

Now, let's initialise typescript by running

$ npx tsc --init

you'll notice a new file will appear on you project, called ts-config.json.

Let's open it add look for "jsx", you'll notice the line will be probably be commented, uncomment and adapt to look like

"jsx": "react",

this change will allow ts-node to deal with the react.js files.

Now, let's rename our app.js file to app.ts

$ mv app.js app.ts

In order to be able to use the react view engine, open the app.ts file and after

var app = express();

add

app.set("views", __dirname + "/views")
app.set("view engine", "tsx")
app.engine("tsx", require("express-react-views").createEngine())

at the end of the file, right before module.exports = app, we also need to adjust the port, because that parte was being configured on the bin/www file, for that reason you need to add

const port = 3000

app.listen(port, () => {
  console.log("Listening on port " + port)
})

finally, on the views folder, create a new file called index.tsx with the following content

import React from "react"

const HelloMessage = (props: any) => <div>Hello {props.title}</div>

module.exports = HelloMessage

Ok, now let's boot up our express application to see if everything is working fine.

$ npm run start

the output will be something like

> express@0.0.0 start /Users/pedroresende/Projects/express
> ts-node ./app.ts

Listening on port 3000

Now all you need to do is open you browser with the url http://localhost:3000.