pertrai1 pertrai1 - 1 year ago 214
Javascript Question

es6 import from underscore

I wanted to double check to make sure I understand imports enough to know if it is ok to do

import {_.identity} from 'underscore'
opposed to
import _ from 'underscore'
? That is the only use of underscore if the particular file.

Thank you for your help

Answer Source

Looks like you're very close!

There are a few ways to do this.

IMO the cleanest way to do this goes like this:

import { map, reduce, somethingElse } from 'underscore'

Allowing you to call those methods as so:

map(things, thing => {

The '{ map, reduce } = ...' part is es6s destructuring assignment. See the Mozilla docs page for more details on this!

Another way would be to do:

import map from 'underscore/map'
import reduce from 'underscore/reduce'

Personally, I'm not a big fan of this since it can start being a bit more cumbersome as more methods are pulled in but it does have one slight advantage, you can name the reference as you like:

import mappy from 'underscore/map'
import reducerify from 'underscore/reduce'

Though I wouldn't advise using those names!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download