[英]SyntaxError: Unexpected token using async and babel in koa
我有使用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
您正在獲取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
}
]
]
}
參考鏈接
將nodejs版本升級到v7.6.0或更高版本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.