2

I am trying to run a server using es6 modules but crashes every time I do it and works whenever I use it with es5error message

I have babel installed and have "preset": ["env"] in my .babelrc file but whenever I run it, I have a "syntax error: Invalid or unexpected token". And this is not on one particular project, this is the third project where am experiencing this

import http from 'http';
import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';

// setting up express application
const app = express();

const hostName = '127.0.0.1';
const port = 3000;
const server = http.createServer(app);

// logs request to the console
app.use(logger('dev'))

// Parse incoming data requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

// making a request to the server
app.get('*', (req, res) => res.status(200).send({
    message: 'Welcome to the default API route',
}));

server.listen(port, hostName, () => {
    console.log(`Server running at http://${hostName}:${port}/`);
});

it supposed to bring out "Welcome to the default API route" to the console but instead, it is an error message. And if the repo is needed, i will gladly supply it

1 Answers1

6

ES6 is not yet supported in the Node runtime by default. You can integrate it like this:

  1. npm i esm && npm i -D nodemon

  2. In your package.json, add this to scripts:

"start": "nodemon -r esm index.js"

(make sure the index.js part of the script matches the name of your server entry point file)

  1. Run npm start
Len Joseph
  • 1,214
  • 9
  • 20
  • When i tried what you said I should, i got this error below and it occured during installation of esm **npm WARN bookstore@1.0.0 No repository field. npm ERR! Maximum call stack size exceeded npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Adewale\AppData\Roaming\npm-cache\_logs\2019-07-10T14_19_21_339Z-debug.log** – Didymus Orotayo Jul 10 '19 at 14:22
  • Holy smokes, I created a stackoverflow on stackoverflow. I will look into why this is happening. – Len Joseph Jul 10 '19 at 14:31
  • Unless you're open to upgrading to Node v.12.0, which is experimental, it looks like require statements are a better bet: https://stackoverflow.com/questions/39436322/node-js-syntaxerror-unexpected-token-import – Len Joseph Jul 10 '19 at 14:44
  • yeah, require works fine but the moment i switch to using es6 modules, it starts acting up – Didymus Orotayo Jul 13 '19 at 18:15
  • ES6 imports are not supported in Node until v12 – Len Joseph Jul 13 '19 at 20:38