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.
typeof require === 'undefined'
?
It's not part of the specs https://nodejs.org/api/globals.html#globals_global
That means that in browsers if you're in the global scope var something will define a global variable. In Node.js this is different.
When some things are different they are most definitely not part of any spec.
Doesn't this make it immensely easier to create files that will work if they are imported OR required?
Don't see how. In node.js this.SOMETHING = 10
only changes one name (module.exports
) for another (this
). Nothing more.
And if you'll try to import test2.js
into the browser using webpack or <script type="module" src="..."></script>
you will get TypeError: undefined has no properties
in both cases.
typeof require === 'undefined'
Maybe you would be better off with browser-require
, browserify
or something like that.