I have the code:
// lib.js
var a = "a";
export var b = "b";
// main.js
console.log(a); // "a" variable is not available in a global scope
import {b} from "lib";
console.log(a); // is "a" variable available in a global scope or only in a module scope?
Can I use "a" variable in a global scope after module importing or is it available only in a module scope? Will ES6 modules have a similar working principle like this trick:
// module
exports.module1 = (function(){ var a = "a"; })(); // "a" variable is not available in a global scope
Can I use "a" variable in a global scope after module importing or is it available only in a module scope?
It's only available inside the module it was declared in.
Will ES6 modules have a similar working principle like this trick: [...]
Basically yes.
ES6 has these kinds of scopes, order from "top" to "bottom":
- Global scope
- Module scope
- Function scope
- Block scope
You can do globalThis.a = "a"
and access it after that module has loaded. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
lets say you are exporting something to another module. example you are exporting var b = 'b'
, but you are not exporting the var a = 'a'
. this means you are only able to use var a = 'a'
in lib.js
, It is local to the module it was declared in and only can be used in that module. var a
is scoped to the lib.js
module.