What imports a module from a “module” when there is no default export, and why is it different from import * as a module?

I am new to JavaScript and have been struggling with import recently. One thing that I can’t cover my head with.

In older node modules (mainly those that came to see the light before ES6) that can be installed using npm, such as express , the default export is usually not defined.

My IDE (WebStorm) marks the following line: the default export export is not declared in the notification of the imported module.

 import express from 'express'; 

You can get around this message by trying to import the entire module as an alias using

 import * as express from 'express'; 

By implicitly telling my IDE to simply import everything and call it express , however, this leads to the fact that express is not a functional error when trying to create an application instance on the next line.

 const app = express(); 

In particular, the original import works (without an alias).

What exactly is imported using the import statement without an alias when the default export is not set? I would think that this is the whole module, but it is not.

+8
javascript import ecmascript-6
source share
1 answer

What imports import Module from 'module' when no default export is specified?

Nothing. In fact, creating an instance of the module will throw a SyntaxError when something is imported that is not exported or exported several times from the imported module.

Why is it different from import * as Module ?

Because import * simply imports an object namespace module that has export as properties. If you do not export anything, this will be an empty object.

Older, pre-ES6 node modules do not usually specify a default export.

This means that you cannot import them as an ES6 module. It seems your IDE is expecting this to result in a warning.

So what happens if you refer to them in an import declaration? Your module loader can do something with it, and the HostResolveImportedModule will return a module record that is not the source text of the "ES6 Module" - that is, it can do all implementation-dependent CommonJS modules.

+6
source share

All Articles