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?
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 .
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.
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';
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With