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

前端 未结 2 738
终归单人心
终归单人心 2020-12-06 18:14
import utilityRemove from \'lodash/array/remove\';
import utilityAssign from \'lodash/object/assign\';
import utilityRandom fr         


        
相关标签:
2条回答
  • 2020-12-06 18:46

    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();
    
    0 讨论(0)
  • 2020-12-06 19:06

    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';
    
    0 讨论(0)
提交回复
热议问题