简体   繁体   中英

Object destructing import from library

Im trying to use object destructing imports in my code.

I would like to import only map and extend in my component.

Would I do

import { map, extend } from lodash;

How can I use it in my code?

Javascript also has a map, so if I do

let arr = [1,3,4];
arr.map((item) =>  console.log(item))

How can I refer to lodash map, not the actual map method?

PS: Im trying to understand object destructing methods. I know I can use ES6 map, this is just an example.

This is a default import .

import _ from 'lodash';
_.map(...);

This is a named import .

import { map } from 'lodash';
map(...);

Using map() as a method of the default import and as a standalone function are essentially the same (with the only meaningful difference being the value of this ). Which syntax works is up to the library you are importing. You can only use a default import if the library defines a default export and same for named imports / exports. Both can also be used at the same time, though this is a bit unusual.

The default import can be named whatever your heart desires. If you want to confuse people and pretend that Lodash is jQuery, you can do so.

`import $ from 'lodash';`

On the other hand, named imports have specific names that they are bound to. So unlike the default import, trying to use the named import syntax on $ vs _ refers to an entirely different object and will throw if not defined as an export within the library.

// These are very different.
import { $ } from 'lodash';
import { _ } from 'lodash';

If it becomes necessary, you can "rename" a named import.

import { map as crazyFunc } from 'lodash';

In the above case, crazyFunc can be named whatever your heart desires, but map must remain as-is, otherwise it will refer to an entirely different object and will throw if not defined as an export within the library.

It may help to understand that these are equivalent.

import { default as _ } from 'lodash';
import _ from 'lib';

The latter is simply sugar for the former. And the default export syntax is sugar for creating a named export with the name default .

For more info (including features not covered here), see ES6 modules syntax .

Full example:

import { map } from 'lodash';
const squares = map([4, 8], (n) => {
    return n * n;
});
console.log(squares);  // => [16, 64]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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