How to run simple app with koa2?

后端 未结 2 884
鱼传尺愫
鱼传尺愫 2021-01-21 19:18

Problem

I am trying to run simple http server using koa2, but have problems running it.

It uses es6 that is expected to work in future node.js v

2条回答
  •  春和景丽
    2021-01-21 19:49

    Solution

    I was able to find workaround and will describe solution that includes installing Babel module

    Step 1 - Install Babel and required presets

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

    Step 2 - Create index.js file with babel-core/register requirement

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

    Step 3 - Put your sample code inside of app.js

    import Koa from 'koa';    
    const app = new Koa();
    
    // Setup handler.
    app.use(async ctx => {
        ctx.body = "Hello World!";
    });
    
    // Start server.
    app.listen(3000);
    

    After running node index.js server works like a pie and import, async, await are being processed properly.

    References

    • koa2 sources
    • Documentation should include an example of babel configuration
    • Using Babel
    • Installation Guide

提交回复
热议问题