Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import into properties using ES6 module syntax (destructing)?

import utilityRemove from 'lodash/array/remove';
import utilityAssign from 'lodash/object/assign';
import utilityRandom from 'lodash/number/random';
import utilityFind from 'lodash/collection/find';
import utilityWhere from 'lodash/collection/where';

let util;

util = {};

util.remove = utilityRemove;
util.assign = utilityAssign;
util.random = utilityRandom;
util.find = utilityFind;
util.where = utilityWhere;

Is there a better way to do the above using ES6 module system?

like image 490
Gajus Avatar asked Aug 20 '15 17:08

Gajus


People also ask

How can I conditionally import an ES6 module?

To conditionally import an ES6 module with JavaScript, we can use the import function. const myModule = await import(moduleName); in an async function to call import with the moduleName string to import the module named moduleName . And then we get the module returned by the promise returned by import with await .

What is ES6 Destructuring?

Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.


2 Answers

If these are the only symbols in your module, I would shorten the names and use the new object shorthand to do:

import remove from 'lodash/array/remove';
import assign from 'lodash/object/assign';
import random from 'lodash/number/random';
import find from 'lodash/collection/find';
import where from 'lodash/collection/where';

let util = {
  remove,
  assign,
  random,
  find,
  where
};

If that could cause conflicts, you might consider moving this section to its own module. Being able to replace the lodash methods while testing could potentially be useful.

Since each symbol comes from a different module, you can't combine the imports, unless lodash provides a combined import module for that purpose.

If you're simply exporting a symbol without using it, you can also consider this syntax:

export remove from 'lodash/array/remove';
export assign from 'lodash/object/assign';

Which, to anyone importing and using your module, will appear as:

import {remove, assign} from 'your-module';
like image 125
ssube Avatar answered Oct 13 '22 00:10

ssube


You can do this in a utils module:

//utils.js

export remove from 'lodash/array/remove';
export assign from 'lodash/object/assign';
export random from 'lodash/number/random';
export find from 'lodash/collection/find';
export where from 'lodash/collection/where';

and use it like this:

import * as util from './utils';

...

util.random();
like image 32
Gabriel McAdams Avatar answered Oct 13 '22 01:10

Gabriel McAdams