I accidentally used require()
on a javascript module meant to be used with the browser.
The module set this['libraryName'] = ...
.
I noticed that it actually worked.
So, I created 2 files:
test1.js
console.log( require('./test2.js'))
test2.js
console.log(this === module.exports)
this.SOMETHING = 10
The result?
$ node ./test1.js
true
{ SOMETHING: 10 }
$
I didn't expect this!
That true
means that module.exports is the SAME as this
in the global context.
- Is that new?
- Is that part of the specs?
- Doesn't this make it immensely easier to create files that will work if they are imported OR required?
- If this works, why do we still do the whole check
typeof require === 'undefined'
?- Have I been oblivious to something this important for years?