Combine Typescript with NextJS and Express
Today we will setup project from scratch and combine TypeScript, NextJS and Express together. at Medvine we had NextJs combine with Express to be standard stack for internal service. and today I will add Typescript into that stack. so let get started.
Install standard NextJS with Typescript
NextJs provide script that will lead us to getting started with NextJs and Typescript easier by this command.
npx create-next-app --example with-typescript <project_name>
Let run yarn dev and see what we got at http://localhost:3000/
And if we look and pages directory. we will see file index.tsx and about.tsx which is extension of typescript file.
Then we need to install express
yarn add express
yarn add @types/express nodemon --dev // for typescript checker
We need to create file name server.tsx for run express and use this code.
Change script on package.json file to.
"scripts": { "dev": "nodemon -w controllers -w server.tsx --exec yarn type-check", "build": "next build", "start": "next start", "type-check": "tsc && node dist/server.js"}
On dev command we use Nodemon to watch file change at folder controllers and file server.tsx. if have any change will run type-check command and run dist/server.js
And we need to change config at tsconfig.json like this.
outDir — directory of output files after compiled script.
jsx — need to be react for es6 command.
module — use commonjs so we can use es6 import.
include — source directory of file before complier.
Then run yarn build for build NextJS first and after that we run yarn dev for watch file and complier.
Goto http://localhost:3000/ we will see same pages. but this time we see log that said server ready on port 3000. that mean we combine express to this project successfully.
Next step. we need to create controller endpoint. create new folder call controllers and create file name hi.tsx then add this code.
Go back at server.tsx file. import hi.tsx and use this controller at app block scope. the complete file should look like this.
Then run http://localhost:3000/hi we will see result of new endpoint
I appreciated all cup of coffee. you can donate coffee at button below.
Now we can use Typescript with NextJS and Express. you can look all source code here.