简体   繁体   中英

koa-static: async function isn't supported by old Node.js

In my Koa project, I use the koa-static to serve the static files. And the simple project it just goes as following:

var koa = require('koa');
var serve = require('koa-static');
var app = new koa();
app.use(serve('./public'));
app.listen(3000);

We plan to put all the static files in the public folder.

But I get the following error message when I want to run the Node app.

 koa-static@4.0.1@koa-static\\index.js:39 return async function serve (ctx, next) { ^^^^^^^^ SyntaxError: Unexpected token function 

So my Node version is 6.11.0 . And the koa-static used async/await function, which is supported by Node.js newer than v7.6.0.

So if I don't plan to update the Node, is there anyway to work around this issue? I manually use Babel to transpile my ES6 code. But for the package, can I babel it?

The thing is that Koa is specifically built around async/await and Node.js 7.6.0 or higher, which is mentioned at GitHub . So package developers are just following the basic standard and most of the time do not bother supporting earlier versions of Node.js. Maybe you should reconsider migrating?

If absolutely not, there are two visible ways to make it work:

  1. Setup package.json step to give you transpile with Babel as part of installation process ( npm install has preinstall and postinstall steps). That way you will have transpiled packages right after installation.
  2. Configure your Webpack (Gulp, Grunt) to preprocess node_modules or specifically koa-static with Babel. Performance degradation could be significant, and this is rather lazy solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM