如何使用ES6模块语法(破坏)导入属性? [英] How to import into properties using ES6 module syntax (destructing)?

查看:157
本文介绍了如何使用ES6模块语法(破坏)导入属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从'lodash / array / remove'导入utilityRemove;
import utilityAssign from'lodash / object / assign';
从'lodash / number / random'导入utilityRandom;
import utilityFind from'lodash / collection / find';
import utility来自'lodash / collection / where';

let util;

util = {};

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

有没有更好的方法来使用ES6模块系统?

解决方案

如果这些是模块中唯一的符号,我将缩短名称并使用新的对象简写:

  import from'lodash / array / remove'; 
import from'lodash / object / assign';
从'lodash / number / random'导入随机数;
import'from'lodash / collection / find';
import from'lodash / collection / where';

let util = {
remove,
assign,
random,
find,
其中
};

如果可能会导致冲突,您可以考虑将此部分移至自己的模块。由于每个符号来自不同的模块,所以不能组合导入,除非lodash提供了一个方法,否则可以在测试过程中替换lodash方法可能有用。



组合导入模块为此目的。



如果您只是简单地导出符号而不使用它,您还可以考虑此语法

  export from'lodash / array / remove'; 
导出从'lodash / object / assign'分配;

哪个导入和使用您的模块的用户将显示为:

 导入{remove,assign} from'your-module'; 


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';

这篇关于如何使用ES6模块语法(破坏)导入属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆