LoginSignup
1
4

More than 5 years have passed since last update.

koa@2でWebアプリケーションを作る

Last updated at Posted at 2016-11-01

koajs概要

Node.js用Webアプリケーションフレームワーク

以下ぐぐってざっくり把握

  • Express開発陣によって開発されている、Expressの後継
  • よりminimalist,modularな設計
  • koaはgeneratorベースだったが、koa@2はasync/awaitベース

ローカルで動かす

Node.js導入

$ nvm install 6.9.1
$ node -v
v6.9.1

package.json

作業ディレクトリを作ってpackage.jsonを生成

$ mkdir APP_NAME
$ cd APP_NAME
$ npm init
$ npm install --save koa@2
$ npm install --save babel-cli babel-preset-es2015 babel-preset-stage-0 babel-polyfill

scriptsとenginesを修正

package.json
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "babel index.js -o app.js",
    "heroku-postbuild": "npm run build",
    "start": "node app.js"
  },
  "engines" : {
    "node" : "6.9.1"
  },

Babelプリセット設定

.babelrc
{
    "presets": ["es2015", "stage-0"]
}

koaミドルウェア導入

評価がまだ心細いが、適当に探して選んでみる。

$ npm install --save koa-router@next
$ npm install --save pug koa-pug

ビュー実装

$ mkdir views
views/index.pug
html
  body
    p Hello #{name}!

アプリケーション実装

index.js
import 'babel-polyfill';
import Koa from 'koa';

const app = new Koa();

const Pug = require('koa-pug');
const pug = new Pug({
    app: app,
    viewPath: './views',
    basedir: './views'
});

const router = require('koa-router')();
app.use(router.routes());

router.get('/', async (ctx, next) => {
  ctx.render('index', {name: 'koa@2'});
})

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

koa@2におけるミドルウェアの使い方は個別に調べる。

  • koa-router
    • 7.xではgetの引数がgeneratorからasync/awaitになっている(ただしこの例ではasyncつけてもつけなくても変わらない)
  • koa-pug

ビルド

$ npm run build

app.jsが出力される

動作確認

$ npm start

ローカルではlocalhost:5000で動作確認できる

Herokuで動かす

$ git init
$ git add .babelrc index.js package.json views
$ git commit -m'initial commit'

$ heroku create
$ git push https://git.heroku.com/......git master

参考

1
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
1
4