将require语句中的所有导出解析为局部变量

时间:2018-03-22 22:34:35

标签: javascript node.js ecmascript-6

我有一个js文件导出一堆这样的函数。

module.exports = {
  setScene : setScene,
  talk1: talk1,
  talk2: talk2,
  talk3: talk3,
  talk4: talk4,
  talk5: talk5,
  talk6: talk6,
  talk7: talk7,
  talk8: talk8,
  talk9: talk9,
  talk10: talk10,
  talk11: talk11,
  talk12: talk12,
  talk13: talk13,
  talk14: talk14,
  talk15: talk15,
  talk16: talk16,
  talk17: talk17,
  talk18: talk18,
  talk19: talk19,
  talk20: talk20,
  talk21: talk21,
  touchnose: touchnose,
  touchchin: touchchin,
  friendos: friendos,
  covermouth: covermouth,
  openmouth: openmouth,
  pointeye: pointeye,
  gameover: gameover,
  wait: wait
};
当我需要文件时,在我的app.js文件中

,有没有办法可以将所有值解构为局部变量?

const { setScene, ...wait} = require('./components/play');

我希望能够在我的app.js中调用函数,而无需在require语句中键入每个值。

1 个答案:

答案 0 :(得分:3)

Yes, there is something clever, please don't do it though. It is not a default for a good reason - lexical scoping (being able to trace every identifier) is really important and useful. Doing this will not only slow down your code and only work when not in strict mode - it will also be confusing.

with(require('./components/play')) {
  // all exports are available here
}