1

I have a js file exporting a bunch of functions like so.

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

in my app.js file when I require the file, Is there a way I can destructure all of the values into local variables?

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

I'd like to be able to call the functions in my app.js without typing in every single value in the require statement.

Jeremy Nelson
  • 276
  • 8
  • 16

1 Answers1

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
}
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Nice one :) `with` can always surprise one... – Jonas Wilms Mar 23 '18 at 00:05
  • @JonasW. thanks, this is actually explicitly the purpose of `with` - to introduce dynamic scoping and why it is banned in strict mode. Most people think strict mode is for "nicer code" but it's actually for lexically scoped code so we could do https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/37199.pdf . Except for a few exceptions (which strict mode seals) JavaScript is lexically typed (so identifiers don't just 'appear' with values, except `this`). – Benjamin Gruenbaum Mar 23 '18 at 00:10
  • Thanks for the additional info. https://stackoverflow.com/questions/48270127/can-a-1-a-2-a-3-ever-evaluate-to-true/48270313#48270313 is also somehow related :) – Jonas Wilms Mar 23 '18 at 03:09