简体   繁体   English

node.js (ES6 / Babel) 中 import X 和 import * as X 的区别?

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

I have a node.js library lib written in ES6 (compiled with Babel ) in which I export the following submodules:我有一个用 ES6 编写的 node.js 库lib (用Babel编译),我在其中导出以下子模块:

"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);

I can see the proper output and it work as expected { config: ... } .我可以看到正确的输出,它按预期工作{ config: ... } However, if I try to include the library like this:但是,如果我尝试包含这样的库:

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

it will be undefined .它将是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';

is asking for an object with all of the named exports of 'lib'.正在请求一个对象,其中包含所有命名为“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';

is asking for the default export of lib .要求default导出lib eg例如

export default 4;

would make lib === 4 .将使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
};

Just adding to Logan's solution because understanding import with brackets, * and without solved a problem for me.只是添加到Logan 的解决方案中,因为理解带括号的导入,* 并且没有为我解决问题。

import * as lib from 'lib';

is the equivalent of:相当于:

import {config, db, storage} as lib from 'lib';

Where the * is similar to a wildcard that imports all of the export var from lib.其中 * 类似于从 lib 导入所有export var的通配符。

export var config;
export var db;
export var storage;

Alternatively, using:或者,使用:

import lib from 'lib';

Allows you to only access the default export:允许您仅访问默认导出:

// lib.js
export default storage;

Using {} also only imports specific components from the module, which reduces the footprint with bundlers like Webpack.使用 {} 也仅从模块导入特定组件,这减少了 Webpack 等打包程序的占用空间。

While:尽管:

import storage, { config, db } from './lib'

would import all modules including export default storage;将导入所有模块,包括export default storage;

See Dan Abramov's answer: When should I use curly braces for ES6 import?请参阅 Dan Abramov 的回答: 何时应使用花括号进行 ES6 导入?

import X from Y; is a syntax sugar.是一种语法糖。

import lib from 'lib';

is equal to等于

import { default as lib } from 'lib';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM