Using Koa2 with TypeScript

| 分类 FRONTEND  | 标签 typescript  nodejs  koa2 

Building Web Apps with Koa and TypeScript

Since the early days of NodeJS, Express has been the de-facto standard web framework for NodeJS developers. However, JavaScript has come a long way in the last few years, and features like promises and async functions have made it possible to build smaller and much more robust web frameworks.

Koa is such a framework. It has been built by the team behind Express to take advantage of the latest JavaScript and NodeJS features, specifically async functions.

Unlike Express and other node frameworks such as Hapi, Koa does not require the use of callbacks. This removes a huge potential souce of difficult to trace errors and makes the framework very easy to pick up for new developers.

Now I’ll try to build a new web application project using Koa and TypeScript below.

Getting Set up

Koa requires a version of Node with async function support, so before starting make sure of you have Node8.x(or above) installed.

Let’s start out with a new directory.

proj/
   ├─ src/
   └─ dist/

Now we’ll turn this folder into an npm package.

npm init

You’ll be given a series of prompts. Change your entry point, use ./dist/main.js. You can always go back and change these in the package.json file that’s been generated for you.

Install dependencies

npm install -g gulp-cli
npm install koa koa-router
npm install --save-dev gulp gulp-typescript @types/koa @types/koa-router

Now in the root of project, create a new tsconfig.json file and add the following content:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2017",
    "noImplicitAny": true,
    "types": [
      "koa"
    ]
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

Note above that we configure TypeScript to transpile to ES2017 — this ensures that we take advantage of Node’s native async / await functionality.

Then create a new gulpfile.js file and add the following content:

var gulp = require("gulp");
var ts =require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");

gulp.task("default", function(){
  return tsProject.src().pipe(tsProject()).js.pipe(gulp.dest("dist"));
});

Creating the server

As Koa is a microframework at its core, it is very straightforward to get it up and running.

In your project directory, create a src folder, and inside it create a new file main.ts with the following contents:

import * as Koa from 'koa';
import * as Router from 'koa-router';

const app = new Koa();
const router = new Router();

router.get('/*', async (ctx) => {
    ctx.body = "Hello Vincen!";
});

app.use(router.routes());

app.listen(3000);

console.log("Server running on port 3000");

Running the server

In root of project, running the following command:

gulp
node dist/main.js

Now you should be able to access http://localhost:3000/ in your browser.

Building the Application — Adding Middleware

The main Koa library consists of just the basic HTTP functionality. To build a full web application we’ll want to add appropriate middleware, such as for Logging, Error Handling, CSRF Protection, etc.

In Koa, middleware is essentially a stack of functions, create via app.use(). When a web request is received, it is passed to the first function in the stack. That function can process the request, then optionally pass it on to the next middleware function.

Let’s extend example above to include a middleware function that logs the URL of each web request to the console:

import * as Koa from 'koa';
import * as Router from 'koa-router';

const app = new Koa();

app.use(async (ctx, next) => {
    // Log the request to the console
    console.log("URL: ", ctx.url);
    // Pass the request to the next middleware function
    await next();
});

const router = new Router();

router.get('/*', async (ctx) => {
    ctx.body = "Hello Vincen!";
});

app.use(router.routes());

app.listen(3000);

console.log("Server running on port 3000");

In the example above we now define two middleware functions:

  • The first middleware function takes the Url from the request context (ctx.url) and outputs it to the console using console.log().

  • The function then does await next() which tells Koa to pass the request down to the next middleware function in the stack.

  • The second middleware function comes from koa-router — it uses the url of the request to match the route we configured via router.get().

Then access http://localhost:3000 again.

Standard Middleware

Obviously, you don’t really want to be reinventing the wheel for your web apps. Depending on the types of app you want to create, the following middleware could be useful:


上一篇     下一篇