Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

proper way of using es6 classes in a nodejs project

Tags:

I'd like to be able to use the cool es6 classes feature of nodejs 4.1.2

I created the following project:

a.js:

class a {
  constructor(test) {
   a.test=test;
  }
}

index.js:

require('./a.js');
var b = new a(5);

as you can see I create a simple class that it's constructor gets a parameter. and in my include i require that class and create a new object based on that class. pretty simple.. but still i'm getting the following error:

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/ufk/work-projects/bingo/server/bingo-tiny/index.js:1:63)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)

any ideas why ?

like image 738
ufk Avatar asked Oct 11 '15 08:10

ufk


People also ask

Does node support ES6 classes?

Finally es6 classes have landed in Node.

Can you use classes in Nodejs?

Lots of people don't know it, but you can use and extend real classes in Node. js already. There's a few drawbacks, but once you learn about them, they're really not drawbacks but postive things, that will make your code faster and better.

Why should we use ES6 classes?

ES6 classes are syntactic sugar for the prototypical class system we use today. They make your code more concise and self-documenting, which is reason enough to use them (in my opinion).


1 Answers

Or you can run like this:

node --use_strict index.js

like image 120
smirnov Avatar answered Sep 28 '22 10:09

smirnov