⚠️ This lesson is retired and might contain outdated information.

Refactor Your Router and Route Definitions into Separate Files

Laurie Barth
InstructorLaurie Barth
Share this video with your friends

Social Share Links

Send Tweet

Main.js gets cluttered quickly with all of the routes we've defined. We can break out the router into a separate file, and further break out individual chunks of route records if we want.

Instructor: [00:00] To start our refactoring efforts, we'll create a new folder called router. In it, we'll create a file called index.js. To start, we'll copy everything from our main.js file into index.js. We'll remove the new view statement since that's not router specific. That allows us to get rid of one of our imports.

[00:31] In order to use all of this information, we need to export it. We'll export default router. We can go back to our main.js file and remove everything about a router definition, since it's now duplicated in our index.js file. We'll remove the unused imports as well.

[00:56] Now we want to import out router from router/index. Its use is the same as before inside our new Vue application, but it doesn't work. This is because our relative paths inside index.js are no longer accurate, so we'll adjust those.

[01:22] On refresh, everything works as it should. We can see that our main.js file is quite small now. However, we'd like to refactor a step further. We'll make an additional file called blog routes inside our router folder. Inside that file, we'll create a new constant in array, we'll call it blog routes.

[01:55] We'll take our entire blog route record including the children and remove it from our index.js file. Instead, we'll place it in this new blog routes array. We need to move the imports that we're using into our blog routes files. We can remove the now unused imports from index.js.

[02:23] In order to use this blog routes array, we need to export it. We'll do that here using the default keyword and name it blog routes. In our index file, we'll now import blog routes from ./blogRoutes.

[02:47] In order to use it, we'll make use of the spread operator, which will select each individual item in our blog routes array and place it in our routes array. If we navigation to blog/1234, we'll see that this route is still successfully working.

[03:10] Our refactor gives us a very small main.js file. Most of our routes are defined in the index.js file inside our router folder and additional routes can be found in blogRoutes.js.