👋

【2024】Express + TypeScriptの環境構築をしてみる

2024/11/24に公開

環境構築

npm初期化

npm init -y

ライブラリ導入

npm i express 
npm i -D typescript
npm i -D ts-node
npm i -D nodemon
npm i -D @types/express @types/node

tsconfig設定

npx tsc --init
    "rootDir": "./src",                                  /* Specify the root folder within your source files. */
    "outDir": "./dist",                                   /* Specify an output folder for all emitted files. */
    "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */

プログラム

mkdir src
touch src/index.ts
import express, { Request, Response, Application } from "express";
const app: Application = express();
const port = 3001;

app.get("/", (req: Request, res: Response) => {
  res.send("Hello World!");
});

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

tsをjsにコンパイルしてnodeで実行

npx tsc --build
node dist/index.js

実行スクリプトの追加

  "scripts": {
    "build": "tsc --build",
    "start": "node dist/index.js",

nodemon対応

  "scripts": {
    ...
    "dev": "nodemon ./src/index.ts",
npm run dev


> backend@1.0.0 dev
> nodemon ./src/index.ts

[nodemon] 3.1.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node ./src/index.ts`
Example app listening on port 3001!

gitignore

node_modules
dist/
*.tsbuildinfo

Discussion