LoginSignup
10
13

More than 3 years have passed since last update.

Next.js+Typescript+Express環境をサクッと構築する

Last updated at Posted at 2020-01-10

create-next-app のexampleは便利だけど、「Next.js+Typescript+Express」の環境を作るテンプレートがなく、結構調べました;;
でも、結果としてとても簡単に導入できることがわかったので、メモがてらqiitaに投稿。

1. プロジェクト作成

下記コマンドでカスタムサーバを使ったtypescriptのプロジェクトを作成

$ create-next-app --example custom-server-typescript {ProjectName}

2. expressパッケージと型定義追加

$ yarn add express
$ yarn add --dev @types/express

3. server/index.tsx を修正

下記に書き換える


import next from 'next'
const express = require('express')
const port = parseInt(process.env.PORT || '3000', 10)
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()
  server.get('*', (req: any, res: any) => {
    return handle(req, res)
  })
  server.listen(port, (err: any) => {
    if (err) throw err
    console.log(`> Ready on ${process.env.CLIENT_URL || `http://localhost:${port}`}`)
  })

})

4. 起動

$ yarn dev
10
13
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
10
13