How to run Node.js app with ES2017 features enable

2019-01-19 15:31发布

问题:

I'm new to Node and created an app that has some async/await syntax in it like so:

const express = require('express');
const app = express();

const someLibrary = require('someLibrary');

function asyncWrap(fn) {
  return (req, res, next) => {
    fn(req, res, next).catch(next);
  };
};

app.post('/getBlock', asyncWrap(async (req,res,next) => {
  let block = await someLibrary.getBlock(req.body.id);
  [some more code]
}));

app.listen(process.env.PORT || 8000);

It works fine on my machine but when I deploy to Heroku I get an error because the syntax is not supported:

2017-03-23T10:11:13.953797+00:00 app[web.1]: app.post('/getBlock', asyncWrap(async (req,res,next) => {
2017-03-23T10:11:13.953799+00:00 app[web.1]: SyntaxError: Unexpected token (

What is the easiest way to get Heroku to support this syntax?

回答1:

Specify the node version you want to use in your package.json: https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

So for async/await support you'll want to specify >= 7.6.0

{
  "engines": {
    "node": ">= 7.6.0"
  }
}


回答2:

From the Heroku documentation here

https://devcenter.heroku.com/articles/getting-started-with-nodejs#declare-app-dependencies

it should be declared in your package.json file which engine(s) should be accessible:

{
  "name": "node-js-getting-started",
  "version": "0.2.5",
  ...
  "engines": {
    "node": "5.9.1"
  },
  "dependencies": {
    "ejs": "2.4.1",
    "express": "4.13.3"
  },
  ...
}