LoginSignup
0
0

More than 1 year has passed since last update.

TypeScript with Nodejs and Express 初期設定

Last updated at Posted at 2023-03-25

image.png

開発環境

image.png

ディレクトリ作成

terminal
    mkdir typescript-with-nodejs-andexpress
    cd typescript-with-nodejs-andexpress

NPM 初期設定

terminal
    npm init -y
    
    {
      "name": "typescript-with-nodejs-andexpress",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
    }

image.png

必要なモジュールのインストール

terminal
    npm i -D typescript @types/express @types/node
    npm i -D nodemon concurrently
    npm i express rimraf dotenv
package.json
    {
        "devDependencies": {
            "@types/express": "^4.17.17",
            "@types/node": "^18.15.9",
            "concurrently": "^7.6.0",
            "dotenv": "^16.0.3",
            "nodemon": "^2.0.22",
            "typescript": "^5.0.2"
        },
            "dependencies": {
            "express": "^4.18.2",
            "rimraf": "^4.4.1"
        }
    }

TypeScript 初期設定

terminal
    npx tsc --init

この、コマンドを入力するとtsconfig.jsonが作成されます。下記の様に設定すると、自動でtsファイルの読み込みとコンパイル先のディレクトリとjsファイルが自動生成されます。
index.tsはsrcディレクトリ内に作成します。

tsconfig.json
    {
      "compilerOptions": {
        "target": "es2016", 
        "module": "commonjs",
        "rootDir": "./src",
        "outDir": "./dist",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "skipLibCheck": true,
      },
      "include": ["./src/**/*"]
    }

image.png

package.jsonの"scripts"の追記

package.json
    {
        "scripts": {
            "build": "rimraf dist && npx tsc",
            "predev": "npm run build",
            "dev": "concurrently -p \"[{name}]\" -n \"TipeScript,JavaScript\" -c \"bgBlue.bold,bgMagenta.bold\" \"npx tsc -w\" \"nodemon -q ./dist/index.js\""
  },
    }

index.ts

index.ts
    import express, { Express, Request, Response } from "express";
    import dotenv from "dotenv";

    dotenv.config();

    const app: Express = express();
    const port = process.env.PORT; //.envファイルにPORT:3000を記述

    app.get("/", (req: Request, res: Response) => {
      res.send("Express + TypeScript Server");
    });

    app.listen(port, () => {
      console.log(`⚡️[server]: Server is running at http://localhost:${port}`);
    });

コンソール

表示もカラーリングされていて見やすいですね!このカラーリングは、npm i concurrentlyを利用しています。
image.png

demo.gif

ソースコード

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0