About many things

Getting started with Koa v2

I just started using Koa - next generation web framework for node.js and want to share few good things about it.

Hello World!

Basic server written using koa framework looks like this

import Koa from 'koa';
const app = new Koa();

// Setup handler.
app.use(async ctx => {
    ctx.body = "Hello World!";
});

// Start server.
app.listen(3000);

You might notice sample uses async, import and obviously those are not yet supported in current version of Node.js.

Plan is to have full support of next generation javascript in future Node.js releases and for now modules like babel help us.

Babel sample

To run sample first we need to install babel compiler

$ npm install babel-core --save
$ npm install babel-preset-es2015-node5 --save
$ npm install babel-preset-stage-3 --save

Then we need to create start script for it

// set babel in entry file
require('babel-core/register')({
    presets: ['es2015-node5', 'stage-3']
});

require('./app');

After we need to include all next gen js into app.js file and run node index.js to start server.

Future steps

Just after Node.js will add support for next gen js, the only thing that will be required is to remove index.js file and everything else should work like a pie :)

#javascript #node.js #koa #es2015