proper way of using es6 classes in a nodejs project

怎甘沉沦 提交于 2020-01-01 02:01:11

问题


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;


来源:https://stackoverflow.com/questions/33063206/proper-way-of-using-es6-classes-in-a-nodejs-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!