3

Is it possible to do something like var merge = require('lodash').merge with ES6?

Hoping for something like import {lodash.merge as merge} from 'lodash'.

noob-in-need
  • 861
  • 1
  • 7
  • 13

1 Answers1

6

You're really close!

import { merge } from 'lodash';

You can read up on all the different ways to import on MDN

The as keyword simply makes an alias for a member; for example you could shorten a long member name to a shorter one

import { reallyLongMergeMethodName as merge } from 'lodash';
chazsolo
  • 7,873
  • 1
  • 20
  • 44
  • 1
    Lets say it hasn't been exported explicitly. Was just using lodash as an example, but seeing that it doesn't work perfectly. With require syntax you can easily access any property off of the object you require — regardless of if it was individually exported. – noob-in-need Apr 29 '16 at 18:40
  • 1
    @noob-in-need If I understand correctly then, `lodash` is what is being exported, with `merge` as a method that wasn't explicitly exported but goes along with it's parent object. – chazsolo Apr 29 '16 at 18:42
  • Ahh. Of course. It's just destructuring. I actually have a case where I need to access a property of a property of an import object, but that's probably not possible. Thanks. – noob-in-need Apr 29 '16 at 18:53
  • Importing and destructuring aren't the same. You can only import something that the other module exports. If you need a top-level or nested property of something you've imported you need to do the import first and access the properties in subsequent statements. – JMM May 01 '16 at 04:13