Hi there! In our previous article, we told about the way to implement dynamic layout in Vue apps. And since we decided to continue sharing our approaches with the community the next thing we want to tell about in this post, it’s how to make main.js file of your Vue app more clear and readable in a project where you have to use a pretty large number of packages and plugins.
The approach described in this article is not actual for simple small applications, but if you’re gonna build medium or large projects — this article is for you.
Let’s take a look at the main.js file example at the early development stage:
Nothing annoying. But how it will look a bit later?
Here is one of real life examples:
So what’s wrong with that?
As for me, there are at least three points:
1) Each time you’ll need to dive into this part of a project, you’ll have to spend some time to read and realize what’s going on here and in what sequence. It’s just since the file is pretty long itself.
2) Each time you’ll need to comment out some package/plugin to disable its usage, you’ll have to find a chunk with Vue.use(…) and comment out it, then scroll to the top and comment out all related imports. This way is particularly annoying if you have to perform this some large number of times, e.g. when you need to catch some not obvious behaviour and you feel it’s connected with some plugin and you need to toggle its usage during debugging.
3) This long spaghetti is not very convenient when you need to reorder the sequence of code chunks.
So how can this code be organized another way?
Let’s try to wrap each plugin registration into the separate function and let this function will return this to provide the fluent interface. And let’s put this code into the separate app-init.js module. All configuration related stuff we’ll put into app-conf.js. And one more point we should do is to import our new module and make the pipe in the desired sequence in our main.js.
And what about annoying points above?
1) You can really quickly realize what’s going on and in what sequence.
2) You can easily toggle any package/plugin just by commenting out appropriate line in the pipe.
3) You can reorder the sequence of calls in the pipe easily and quickly as well.
I’ll happy if this approach appeared to be useful for you.