Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel NodeJS ES6: SyntaxError: Unexpected token export

I'm trying to use babel to run my NodeJS program, which includes ES6 syntax and exports from the Colyseus library. However, when I run the command:

babel-node server.js

The following error message appears:

export class MyRoom extends colyseus.Room {
^^^^^^

SyntaxError: Unexpected token export

Below is my package.json file:

{
  "name": "app",
  "version": "1.0.0",
  "description": "a description",
  "main": "server.js",
  "scripts": {
    "test": "babel-node server.js",
    "build": "babel-node server.js"
  },
  "author": "henryzhu",
  "license": "ISC",
  "dependencies": {
    "actionhero": "^19.1.2",
    "colyseus": "^0.9.33",
    "easytimer.js": "^2.3.0",
    "express": "^4.16.3",
    "socket.io": "^2.1.0",
    "socketio": "^1.0.0",
    "uniqid": "^5.0.3"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1"
  }
}

Below is my server.js file:

var colyseus = require("colyseus");
var http = require("http");
var express = require("express");
var port = process.env.port || 3000;

var app = express();

app.use(express.static("public", { dotfiles: 'allow' }));

var gameServer = new colyseus.Server({
  server: http.createServer(app)
});

export class MyRoom extends colyseus.Room {
    // When room is initialized
    onInit (options) { }

}

gameServer.listen(port);
like image 320
Adam Lee Avatar asked Mar 24 '19 23:03

Adam Lee


People also ask

How do I fix SyntaxError unexpected token export?

To solve the "Uncaught SyntaxError Unexpected token 'export'", refactor your code to use the CommonJS syntax, e.g. module. exports = {num}; instead of export num = 10; . Copied!

What does Babel node do?

Babel is a JavaScript compiler Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.

How do I export a node js class?

As we just saw, exporting a class can be accomplished by attaching the class as a property of the module. exports object. First, we created a class using a constructor function. Then we exported the class using module.


Video Answer


2 Answers

Add a config file with the following (.babel.config.js):

module.exports = {
    presets: [
        '@babel/preset-env'
    ]
};

Then run:

babel-node --config-file .babel.config.js server.js

like image 129
ryanpcmcquen Avatar answered Oct 19 '22 18:10

ryanpcmcquen


babel-node is presumably expecting the node style module syntax:

module.exports = ...

instead of the es6 style:

export class ...

EDIT:

You might be able to fix it by specifying a .babelrc file like so:

{
    "presets": ["env"]
}

with package babel-preset-env installed

like image 37
jsdeveloper Avatar answered Oct 19 '22 17:10

jsdeveloper