node.js (ES6/Babel) 中 import X 和 import * as X 的区别? [英] Difference between import X and import * as X in node.js (ES6 / Babel)?

查看:34
本文介绍了node.js (ES6/Babel) 中 import X 和 import * as X 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 ES6 编写的 node.js 库 lib(用 Babel 编译)我在其中导出以下子模块:

I have a node.js library lib written in ES6 (compiled with Babel) in which I export the following submodules:

"use strict";

import * as _config from './config';
import * as _db from './db';
import * as _storage from './storage';

export var config = _config;
export var db = _db;
export var storage = _storage;

如果从我的主要项目中包含这样的库

If from my main project I include the library like this

import * as lib from 'lib';
console.log(lib);

我可以看到正确的输出并且它按预期工作{ config: ... }.但是,如果我尝试包含这样的库:

I can see the proper output and it work as expected { config: ... }. However, if I try to include the library like this:

import lib from 'lib';
console.log(lib);

它将是undefined.

有人能解释一下这里发生了什么吗?这两种导入方法不应该是等效的吗?如果没有,我缺少什么区别?

Can someone explain what is happening here? Aren't the two import methods supposed to be equivalent? If not, what difference am I missing?

推荐答案

import * as lib from 'lib';

正在请求一个对象,其中包含所有命名为lib"的导出.

is asking for an object with all of the named exports of 'lib'.

export var config = _config;
export var db = _db;
export var storage = _storage;

被命名为导出,这就是为什么你最终会得到一个像你一样的对象.

are named exports, which is why you end up with an object like you did.

import lib from 'lib';

要求libdefault 导出.例如

export default 4;

将使 lib === 4.它不获取命名的导出.要从默认导出中获取对象,您必须明确执行

would make lib === 4. It does not fetch the named exports. To get an object from the default export, you'd have to explicitly do

export default {
  config: _config,
  db: _db,
  storage: _storage
};

这篇关于node.js (ES6/Babel) 中 import X 和 import * as X 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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