Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ECMAScript-6 import a nested function?

Hi I switched over to ECMAScript-6 javascript syntax a little while ago and am loving it! One thing I noticed and couldn't find a definitive answer on is using nested destructing syntax on an import. What I mean is something like this..

Lets say I have a file that looks like this.

export const SomeUtils = _.bindAll({ //lodash _
    someFunc1(params){
        // .... stuff here
    },
    someFunc2(params){
        // .... stuff here
    },
    someFunc3(params){
        // .... stuff here
    }
});
// ... many more of these

I have been doing something like this to get a specific function

import {Utils} from '../some/path/to/utils';
var {someFunc2} = Utils;

To get to the point.. Is there a way to do a single line import for someFunc2? like how you can do the nested object destruction assignment with brackets? (Aka: {Utils: [{someFunc2}]}) ?

I used to do var someFunc2 = require('../some/path/to/utils').someFunc2; but I can't seem to figure out how to do it with an import statement

like image 477
John Ruddell Avatar asked Oct 18 '22 20:10

John Ruddell


1 Answers

No, ES6 module imports do not provide a destructuring option. The only feature they have are named exports (but without nesting). They are meant to exactly replace your require(…).someFunc2 pattern.


In your specific case, I don't see any reason why you would be exporting a single object as a named export. Just use

export function someFunc1(params){
    // .... stuff here
}
export function someFunc2(params){
    // .... stuff here
}
export function someFunc3(params){
    // .... stuff here
}

so that you then can do

import {someFunc2} from '../some/path/to/utils';
like image 101
Bergi Avatar answered Oct 21 '22 22:10

Bergi