How to run simple app with koa2?

雨燕双飞 提交于 2019-12-04 04:53:32

问题


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 versions and I was wondering how can I run it with node v6.1.0 ?

Code

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

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

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

Output

$ node --version
v6.1.0

$ node --harmony index.js
C:\Users\gevor\WebstormProjects\untitled1\index.js:1
(function (exports, require, module, __filename, __dirname) { import Koa from 'koa';
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:511:25)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:456:32)
    at tryModuleLoad (module.js:415:12)
    at Function.Module._load (module.js:407:3)
    at Function.Module.runMain (module.js:575:10)
    at startup (node.js:160:18)
    at node.js:445:3

Question

I want to know how to run my app?

Similar Issues

  • https://github.com/koajs/koa/issues/621
  • https://github.com/koajs/koa/issues/572

回答1:


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



回答2:


Upgraded your node version to at least 7.6 after that there is no need to transpile your code using babel which is highly avoidable in production.Node >7.6 version support async/await which is very powerful.



来源:https://stackoverflow.com/questions/37529156/how-to-run-simple-app-with-koa2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!