Maybe this isn't specific to the CommonJS implementation of JS modules, but my question is about how scope works with importing a module.
CommonnJS: foo.js
var foo = {
bar() {
baz();
}
}
module.exports = foo;
Main JS
const foo = require('./foo.js');
function baz() {
console.log('this is baz');
}
foo.bar();
//-> ReferenceError: baz is not defined
Normally I would expect baz to have been found, but it seems like the module scope is completely isolated. Is that correct? Is there a way or a best practice in what I'm trying to do?
Nothing to do with webpack.
javascript modules only have local context
If you want something to be a part of the global/window context you can use the global
variable
global.baz = baz;
Or better, use dependency injection to pass your callbacks:
var foo = {
bar(baz) {
baz();
}
}
Then can use it:
foo.bar(baz);