Express は軽量な Node.js のウェブ・フレームワークです。
このフレームワークと TypeScript を使ってアプリケーション開発を行える環境を作ります。Node.js はインストール済みの想定で進めます。
パッケージの準備
mkdir app && cd app npm init
ダイアログはデフォルトで大丈夫です(もちろん設定しても良)。package.json というファイルが作られるのを確認します。
基本となるパッケージをインストールします。
まずは express を。
npm install express
次に TypeScript を使うために必要なパッケージ。
npm install -D typscript npm install -D @types/node npm install -D @types/express npm install -D ts-node
view には pug を使うので pug もインストールします。
npm install pug
package.json を編集して build と start ができるようにします。
"scripts": {
"build": "tsc -p tsconfig.json --outDir dist",
"start": "node dist/app.js",
},
TypeScriptの設定
上記の状態で npm build を試しても tsconfig.json がないのでエラーになります。TypeScript の設定 tsconfig.json を作成します。コマンドでテンプレを作ることもできます。
npx tsc --init
最終的に以下のように設定しました。
{
"compilerOptions": {
"lib": ["ES2020", "dom"],
"baseUrl": ".",
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
"strict": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"esModuleInterop": true,
"alwaysStrict": true,
"module": "commonjs",
"moduleResolution": "node",
"noImplicitThis": true,
"target": "ES2020",
"paths": {
"*": [
"src/*"
]
}
},
"include": [
"src/**/*.ts"
],
"exclude": [
"*.d.ts",
"node_modules"
]
}
アプリケーションの設定
次にアプリケーションの設定を行なっていきます。まずは、メインとなる app.js から。ポート3000でサーバを立ち上げます。ビューや静的ファイルのディレクトリも設定しています。ルーティングの設定は別ファイルから読み込むようにしています、次のファイルでルーティングの設定を記述します。
import express from 'express';
import path from 'path';
import indexRouter from './routes/index';
const app = express();
// view engine setup
app.set('views', 'views');
app.set('view engine', 'pug');
app.use('/static', express.static('public'));
app.use(express.static(path.join(__dirname, 'public')));
// router setup
app.use('/', indexRouter());
const port = '3000';
app.set('port', port);
app.listen(port, () => {
console.log(`App listening on port ${port}`);
});
続いてルーティングの設定です。ルートパスへのリクエストを受け取ってレスポンスに index.pug を返す設定です。
export default router;
import express, { Request, Response, NextFunction, request } from "express";
function router(options = {}) {
// @ts-ignore
const router = new express.Router(options);
return router
.get('/', (req: Request, res: Response, next: NextFunction) => {
res.render('index');
});
}
最後に pug ファイルも書いておきますが、一旦は適当な内容で作成してます。
p Hello, world!
サーバ起動
ここまで準備できたらいよいよサーバを立ち上げることができます。一度 build してから npm run start を実行するとサーバが立ち上がります。 localhost:3000 にアクセスして Hello, world! が表示されていれば完成です。
npm run build npm run start
おわりに
エラーページを設定したり、ビューを充実させたり、静的ファイルを追加したり、ミドルウェアを実装したりとまだまだやることは山ほどありますが、サーバを起動できるところまで完了しました。追加の設定は別記事に切り分けたいと思います。


