In the Mr Jeff web team, we recently had a little use case where we wanted to do an apparently very simple thing, but we didn’t find it documented anywhere. So we thought we could share the solution here in case someone else has the same need.

We have our home page available in several countries. They are all very similar (except for the language of the content, of course), but we want to keep them in separate Vue components because we need to be able to tweak the structure of the page for a specific country. So we have a wrapper component where we render another component based on the URL, and we lazy-load those child components so we only download them if we need them.

So HomePage.vue looks something like this:

Up until recently, we were totally fine with this. The company was only present in a few countries, and we had to launch maybe one new country every few months. Now, however, Mr Jeff’s expansion plans have become much more ambitious, with at least a couple of new countries launching every month, so we’re doing our best to make the process of opening new countries as easy and painless as possible. So, manually adding new imports here wasn’t a good option anymore.

So, going back to the code, the idea was simple: using an already existing array of active countries to import all the HomePageXX components. “Easy!”, I thought. “I just have to build an array of those import functions and pass it to the components object, what could go wrong?”

My first attempt was this:

Don’t do this at home kids

But, oh no, that didn’t work :(

Fortunately, as soon as I saw what kind of errors the console was throwing, I discovered the cause — the syntactic sugar of ES6 was hiding the full syntax from my eyes. I’m so used to write the component block like that, that I didn’t realize they actually represent both a key and a value.

In other words, I was wrongly assuming that this…

…was an equivalent to this.

But of course, that’s not a key-value pair, which is what objects contain. What we really want is this:

So, instead of making homepageComponents an array, we can declare it as an object, with the import functions as the values, and the component names as the keys.

This is the final, working code!