Mazzy Mazzy - 7 months ago 131
Javascript Question

SyntaxError: Unexpected token using async and babel in koa

I have this simple app made using the last alpha version of Koa. In order to use `async/wait Babel.Js is required.

'use strict';

// babel registration (runtime transpilation for node)
require('./server.babel');

const Koa = require('koa');
const app = new Koa();

// define logger - this will be always executed
const logger = async (context, next) => {
const start = new Date;
await next();
const ms = new Date - start;
console.log(`${context.method} ${context.url} - ${ms}ms`);
}

const index = (context) => {
context.body = 'Hello World';
}

app.use(logger);
app.use(index);

app.listen(3000);
console.info(`The app is listening on port 3000`);





This is the hook to activate the transpiling.

const fs = require('fs');

let config;

try {
config = JSON.parse(fs.readFileSync('./.babelrc'));
} catch (error) {
console.error('==> ERROR: Error parsing your .babelrc.');
console.error(error);
}

require('babel-core/register')(config);


and this is the config file:

{
"plugins": ["transform-async-to-generator"]
}


Unfortunately when I try to run the project I get the following error:

const logger = async (context, next) => {
^

SyntaxError: Unexpected token (
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:404:25)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:457:10)
at startup (node.js:138:18)
at node.js:974:3


I have no idea why I get this error. I'm using the last Node.Js version
5.1.0
and Babel
6.2.1

Answer

You are getting the SyntaxError. That happens because your code is being parsed before Babel can intercept it and convert.

If you want to make async functions work in your first file, you should require this entire file after have registered its hook.

Create a new file start.js with the following

require('babel-register');
require('./index');

Your code in index.js can use async functions, but you can't do it in the start.js.

Also note, that you don't need to read .babelrc by yourself. Babel will do it for you by default.

Contents of .babelrc looks like this

{
  "presets": [
    "es2015",
    "stage-3"
  ],
  "plugins": [
    [
      "transform-runtime",
      {
        "polyfill": false,
        "regenerator": true
      }
    ]
  ]
}

Reference links