当没有默认导出被定义时,从'module'导入模块是什么,为什么它不同于import *作为Module? [英] What does import Module from 'module' import when no default export is defined and why is it different from import * as Module?

查看:1951
本文介绍了当没有默认导出被定义时,从'module'导入模块是什么,为什么它不同于import *作为Module?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JavaScript很新,最近一直在与进口斗争。有一件事我不能包围我的头。

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

在较旧的节点模块(主要是在ES6之前看到光),可以使用npm,如 express ,通常不定义默认导出。

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.

我的IDE(WebStorm)标记以下内容在导入的模块通知中未声明默认导出的行。

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

import express from 'express';

尝试使用

import * as express from 'express';

隐含地告诉我的IDE只需导入所有内容并将其命名为 express ,但是尝试在以下行中实例化应用程序时,导致 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.

当没有定义缺省导出时,使用import语句导入的是什么?我会认为这是整个模块,但它似乎不是这样的。

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.

推荐答案


导入模块从'module'导入当没有默认导出被定义

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

没有。实际上,实例化模块会抛出 SyntaxError 当导入的东西没有从导入的模块导出或导出多次。

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.


为什么不同于 import *作为模块

因为 import * 只是导入一个具有导出为属性的模块命名空间对象。如果不导出任何东西,它将是一个空的对象。

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.


在较旧的ES6之前的节点模块通常没有默认的导出被定义。

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

这意味着您不能将它们导入为ES6模块。您的IDE似乎期待尽管并提出警告。

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

所以如果您在导入声明?您的模块加载程序可能会执行任何操作, HostResolveImportedModule 将返回模块记录这不是源文本 ES6模块记录 - 即它可能会执行任何依赖于CommonJS模块的实现。

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.

这篇关于当没有默认导出被定义时,从'module'导入模块是什么,为什么它不同于import *作为Module?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆