LoginSignup
2
4

More than 3 years have passed since last update.

Node.js + Express で ES6を使う

Posted at

確認環境

node v10.17.0

アプリケーションテンプレートの作成

ここではplay_expressというアプリを作る前提で進めていきます。
※npxコマンドの使用には、npm 5.2.0以降がインストールされている必要があります。

npx express-generator play_express

次に依存関係をインストールします。

cd play_express
npm i

一旦、動作確認をします。アプリのカレントディレクトリで以下のコマンドを実行します。

npm start

このあと、webブラウザからhttp://localhost:3000/にアクセスすると、「Welcome to Express」画面が表示されます。
動作確認を終了するには、npm start実行中のコンソール上で、Cmd(Ctrl)+c を押下します。

Babelのインストール

ES6を使うため、babelをインストールします。

npm i @babel/core @babel/node @babel/preset-env --save-dev

インストールが完了したらアプリのカレントディレクトリに以下の内容で.babelrcファイルを作成します。

.babelrc
{
  "presets": [
    "@babel/preset-env"
  ]
}

package.jsonの修正

startコマンドの内容を書き換えます。

package.json
{
  "name": "play-express",
  "version": "0.0.0",
  "private": true,
  "scripts": {
-    "start": "node ./bin/www"
+    "start": "babel-node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "morgan": "~1.9.1"
  },
  "devDependencies": {
    "@babel/core": "^7.7.2",
    "@babel/node": "^7.7.0",
    "@babel/preset-env": "^7.7.1"
  }
}

動作確認

以下のコマンドで動作確認。

npm start
2
4
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
2
4