【问题标题】:SyntaxError: Unexpected token using async and babel in koaSyntaxError:在 koa 中使用 async 和 babel 的意外令牌
【发布时间】:2016-02-23 04:22:10
【问题描述】:

我使用 Koa 的最后一个 alpha 版本制作了这个简单的应用程序。为了使用 `async/wait Babel.Js 是必需的。

'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`);

这是激活转译的钩子。

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);

这是配置文件:

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

不幸的是,当我尝试运行该项目时,我收到以下错误:

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

我不知道为什么会出现此错误。我正在使用最新的 Node.Js 版本 5.1.0 和 Babel 6.2.1

【问题讨论】:

  • @Teemu 错字???在哪里?
  • @Teemu 字符串模板。新的 es6 功能
  • 是你的“钩子”server.babel 吗?或者是别的什么
  • 我的钩子在 server.babel 里面,你可以看到
  • 我很确定 server.babel 需要你的应用代码,而不是相反。

标签: javascript node.js asynchronous ecmascript-6 babeljs


【解决方案1】:

将 nodejs 版本升级到 v7.6.0 或更高版本

【讨论】:

    【解决方案2】:

    您收到的是SyntaxError。发生这种情况是因为您的代码在 Babel 拦截并转换之前已被解析。

    如果你想让异步函数在你的第一个文件中工作,你应该在注册钩子后require整个文件。

    使用以下内容创建一个新文件start.js

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

    您在index.js 中的代码可以使用异步函数,但您不能在start.js 中使用。

    另外请注意,您不需要自己阅读.babelrc。 Babel 会默认为你做这件事。

    .babelrc 的内容是这样的

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

    参考链接

    【讨论】:

      猜你喜欢
      • 2016-02-12
      • 2017-03-17
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 2017-08-05
      • 2021-03-31
      • 2019-04-20
      相关资源
      最近更新 更多