20
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Next.jsをExpressカスタムサーバ + TypeScriptで動かす設定

Posted at

プロジェクトの作成

npx create-next-app [project-name]
cd [project-name]
# Nextjsで利用するファイル
mkdir src
mv pages src/
mv src/index.js src/index.tsx

# NextjsをTypeScriptでコーディングするために必要なパッケージをインストール
yarn add -D typescript @types/react @types/node

# カスタムサーバとして利用するExpressのパッケージをインストール
yarn add express 
yarn add -D @types/express ts-node

# カスタムサーバで利用するファイルを作成
mkdir server
touch server/index.ts
touch tsconfig.server.json

server/index.tsの編集

Expressをカスタムサーバとして利用する。
以下のように編集する。

import express, { Request, Response } from "express";
import next from "next";

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const port = process.env.PORT || 3001;

async function main() {
  try {
    await app.prepare();
    const server = express();
    server.all("*", (req: Request, res: Response) => {
      return handle(req, res);
    });
    server.listen(port, (err?: any) => {
      if (err) throw err;
      console.log(`> Ready on localhost:${port} - env ${process.env.NODE_ENV}`);
    });
  } catch (e) {
    console.error(e);
    process.exit(1);
  }
}

main();

tsconfig.server.json

{
  "extends": "./tsconfig.json", // tsconfig.jsonの設定を継承する
  "compilerOptions": {
    "module": "commonjs", // Next.jsとExpressの両方を連携させるために、commmonjsを利用する
    "outDir": "dist", // ビルドファイルの出力先
    "noEmit": false // Next.jsはBebelを使用してTypeScriptをコンパイルするので、TSコンパイラはjsを出力しない。設定を上書きする。
  },
  "include": ["server"] // TSコンパイラにserverディレクトリのみをコンパイル対象として認識させる。
}

package.jsonの編集

scriptsを以下のように編集する。

  "scripts": {
    "dev": "ts-node --project tsconfig.server.json server/index.ts",
    "build:next": "next build",
    "build:server": "tsc --project tsconfig.server.json",
    "start": "NODE_ENV=production node dist/index.js"
  },

開発モードで起動

yarn dev

ビルド & 本番起動

yarn build:next
yarn build:server

yarn start
20
16
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
20
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?