简体   繁体   中英

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM