Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing something that's not explicitly exported by a module in Javascript

Tags:

javascript

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.

like image 972
Lane Rettig Avatar asked Mar 28 '16 14:03

Lane Rettig


People also ask

Can you import modules in JavaScript?

You can import modules into a file in two ways, based on if they are named exports or default exports. Named exports are constructed using curly braces. Default exports are not.

What is dynamic import in JavaScript?

Dynamic imports allows one to circumvent the syntactic rigidity of import declarations and load a module conditionally or on demand.

Can you use import with module exports?

The export declaration is used to export values from a JavaScript module. Exported values can then be imported into other programs with the import declaration or dynamic import.

What are the two types of module exports in JavaScript?

There are two types of exports. One is Named Exports and other is Default Exports. Named Exports: Named exports are useful to export several values.


1 Answers

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.

like image 79
ssube Avatar answered Sep 28 '22 08:09

ssube