proper way of using es6 classes in a nodejs projec

2019-03-17 14:46发布

问题:

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 ?

回答1:

Or you can run like this:

node --use_strict index.js



回答2:

i'm still confused about why 'use strict' is needed, but this is the code that works:

index.js:

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

a.js:

"use strict";
class a {
 constructor(test) {
  a.test=test;
 } 
}
module.exports=a;