Reputation: 6948
In Javascript, is there any way to import (or require) an object that's not exported by a module from that module?
I realize that this is likely bad practice, but I wonder if it's possible nevertheless. I have a Python background, so I'm confused by the idea that I can import a module but cannot access all of its data elements in Javascript.
Upvotes: 11
Views: 5134
Reputation: 48337
Not using the module API. A module exports an object and any code importing the module is given a reference to that object ("reference" in the JS sense).
Section 15.2.3 of the spec covers exports and, very verbosely, shows that the export
keyword is used to include some local variable in the module's import/export table. Quite simply, if you don't specify export
, the variable is local to the module scope.
This matches the behavior of legacy IIFE modules, which used function scope to hide their local variables, then exported an object to be made public.
An ES6 module like:
export class Foo {
...
}
export const bar = new Foo();
after being transpiled will look something like:
(function () {
function Foo() {
...
}
var bar = new Foo();
return {
Foo: Foo,
bar: bar
};
})();
Most articles on JS modules (even the fantastic 2ality module writeup) don't mention what happens to un-exported variables.
For comparison, the CommonJS module standard states that modules have a variable exports
and "the module may add its API to as it executes." The CommonJS standard has the only reference I've found so far to only exporting via keyword/object (from module context 2.1):
modules must use the "exports" object as the only means of exporting.
Upvotes: 7