更新日:

Vercel 無料でAPIサーバを立てる TypeScript・Express

タグ

ソースコード

package.json
{
  "scripts": {
    "start": "ts-node src",
    "build": "rimraf dist && tsc",
    "deploy": "npm run build && vercel --prod"
  },
  "devDependencies": {
    "@types/express": "^4.17.8",
    "rimraf": "^3.0.2",
    "ts-node": "^9.1.1",
    "typescript": "^4.0.2"
  },
  "dependencies": {
    "express": "^4.17.1",
    "vercel": "^20.1.0"
  }
}
src/index.ts
import * as Express from 'express';

const app = Express();

// postリクエスト使えるようにする
app.use(Express.json());
app.use(Express.urlencoded({ extended: true }));

app.get('/get/:name', (req: Express.Request, res: Express.Response) => {
  try {
    res.send({ name: req.params.name });
  } catch (error) {
    res.sendStatus(500);
  }
});

app.post('/post', (req: Express.Request, res: Express.Response) => {
  try {
    res.send({ name: req.body.name });
  } catch (error) {
    res.sendStatus(500);
  }
});

app.listen(process.env.PORT || 3000);

console.log('starts');

export default app;
tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/src",
    "target": "es5",
    "sourceMap": false,
    "strict": true,
    "removeComments": true,
    "moduleResolution": "node"
  },
  "include": ["./src/**/*"],
  "exclude": ["./src/test/*"]
}
vercel.json
{
  "version": 2,
  "builds": [
    {
      "src": "dist/src/index.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/.*",
      "dest": "/dist/src/index.js"
    }
  ]
}

コマンド

デプロイ

bash
$ npm run deploy

© 2020- itsumen.com