Reputation: 5925
I have two files: test.js
that contains
var Buffer = require('./Buffer');
and Buffer.js
with
this.foo
when I run them with mocha test.js
, everything works fine, but running mocha --compilers js:babel/register test.js
generates the following error
TypeError: Cannot read property 'foo' of undefined
at Object.<anonymous> (/path/Buffer.js:1:1)
at Module._compile (module.js:460:26)
at normalLoader (/path/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:150:5)
at Object.require.extensions.(anonymous function) [as .js] (/path/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:163:7)
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> (/path/parser_test.js:2:14)
at Module._compile (module.js:460:26)
at normalLoader (/path/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:150:5)
at Object.require.extensions.(anonymous function) [as .js] (/path/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:163:7)
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 /path/node_modules/mocha/lib/mocha.js:192:27
at Array.forEach (native)
at Mocha.loadFiles (/path/node_modules/mocha/lib/mocha.js:189:14)
at Mocha.run (/path/node_modules/mocha/lib/mocha.js:422:31)
at Object.<anonymous> (/path/node_modules/mocha/bin/_mocha:398:16)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
Why is it happening that this
is undefined when I require a module? Please let me know if you need any additional information to reproduce the error.
I use babel 5.5.0 and mocha 2.2.5.
Upvotes: 2
Views: 1080
Reputation: 971
Babel expects that the input it is given is an ES6/ES2015 module. In modules, top-level this
is undefined
by the specification.
babel --blacklist strict script.js
will allow you to disable this behavior, but this is not according to the specification, so this probably isn't the best idea. You can use global
instead to access the global object in node
, as an alternative.
For more information, see the documentation.
Upvotes: 1