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

查看:97
本文介绍了导入X和导入*在node.js(ES6 / Babel)中的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);

它将是未定义

有人可以解释这里发生了什么吗?两种进口方法是不是应该是等价的?如果没有,我缺少什么区别?

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;

被命名为export,这就是为什么你最终得到像你这样的对象。

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

import lib from 'lib';

要求默认 code> LIB 。例如

is asking for the default export of lib. e.g.

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
};

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

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