20

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 ?

7
  • Strict mode Commented Oct 11, 2015 at 9:00
  • don't i need to enable strict mode? it's not enabled by default no ? Commented Oct 11, 2015 at 9:10
  • 1
    You need to enable strict mode, it's not (yet) enabled by default. Commented Oct 11, 2015 at 9:10
  • i added "use strict"; at the beginning of index.js but the results are the same Commented Oct 11, 2015 at 9:14
  • You need it at the beginning of every module. Commented Oct 11, 2015 at 9:14

2 Answers 2

36

Or you can run like this:

node --use_strict index.js

Sign up to request clarification or add additional context in comments.

2 Comments

Much better than putting "use strict" in the scripts. Also, the order of arguments seems to matter: node index.js --use_strict does not work.
Running your entire app in strict mode means you won't be able to use modules that assume you are not running in strict mode. You may find yourself doing a lot of refactoring down the line if you do this.
26

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;

1 Comment

"i'm still confused about why 'use strict' is needed" I think the error message is pretty clear, isn't it? "Block-scoped declarations (let, const, function, class) not yet supported outside strict mode" You need it because class is not yet supported outside of strict mode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.