Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does import Module from 'module' import when no default export is defined and why is it different from import * as Module?

I am pretty new to JavaScript and have been struggling with imports recently. There has been one thing I cannot wrap my head around.

In older node modules (mostly those which came to see the light prior to ES6), which may be installed using the npm, such as express, usually no default export is defined.

My IDE (WebStorm) marks the following line with the Default export is not declared in the imported module notification.

import express from 'express';

This message may be circumvented by trying to import the whole module as an alias using

import * as express from 'express';

implicitly telling my IDE to just import everything and name it express, however doing so then leads to an express is not a function error when trying to instantiate the application on the following line.

const app = express();

Peculiarly the original import (without the alias) works.

What exactly is imported using the import statement without the alias, when no default export is defined? I would think it is the whole module, but it does not seems so.

like image 752
Andy Avatar asked Feb 20 '16 17:02

Andy


1 Answers

What does import Module from 'module' import when no default export is defined?

Nothing. In fact, instantiating the module will throw a SyntaxError when something is imported that is not exported or exported multiple times from the imported module.

Why is it different from import * as Module?

Because import * just imports a module namespace object that has the exports as properties. If you don't export anything, it'll be an empty object.

In older, pre-ES6 node modules usually no default export is defined.

Which means that you cannot import them as an ES6 module. Your IDE seems to expect that though and puts up the warning.

So what happens if you refer to them in an import declaration? Your module loader might do anything with it, and HostResolveImportedModule will return a module record that is not an source text "ES6 module" record - i.e. it might do anything implementation-dependent with CommonJS modules.

like image 115
Bergi Avatar answered Oct 13 '22 01:10

Bergi