Keeping Javascript Simple

Constant discussions about the state of frontend development are going for a while now. And they all touched a nerve or two for everyone. The amount of tools and libraries you need to integrate and keep track of is increasing rapidly. Mix it with the efforts of trying to fix javascript (ES6+) and you forget what you were going to do in the first place.

So I was looking for a way back to the old ways of <script src=”jquery.js”/> but still be able to use a modern library employing aproaches like javascript components, one way data flow, easy and fast dom updates.

I believe my search is over. Vue.js is a frontend framework that can be directly included from your html files, and it is comparable to Angular and React. In this post I want to describe how I use it to have a modern environment without dealing with the likes of npm, webpack, babel, typescript etc..

To go over the specifics of my setup, I put together a simple Google Keep clone just for this post. The code is on github, and there is a running demo that you can check out. The demo does not save anything for obvious reasons.

UI Components

To implement the very basic functionality of Google Keep, three components seems enough. One to view notes, one to create and another one to wrap the note editor in a modal box. Their code can be found from the same github repository.

Backend

Coming from a long Java background, my backend of choice is Spring Boot. It has all the goodies of spring with none of the configuration hassle. But I am not going into any details as it is not the intent of this post. We will also use Thymeleaf as the server side template engine. It will help with the methods used in the next two sections.

Preloading Data

To decrease the number of requests going to the server, you can insert the list of notes to the initial page. Just loading the notes from DB and adding to the mvc model, they will be converted to JSON with thymeleaf’s inline javascript function.

/*[[${notes}]]*/

This line is replaced with the JSON representation of the notes when thymeleaf processes the template.

Single File Components

Vue.js has a feature called single file components. The idea is to keep the template, style and the javascript of a component together. This can be partially done with thymeleaf includes. Since style tags outside of head tag works in recent browsers, it usually works. Unlike .vue files, this aproach does not solve name collisions, so be careful.

Here is the simple code for the note view component.

The Future

I am using this aproach on a medium sized project and wish to avoid the dark side of javascript for as long as possible. And the trends looks good too.

https://insights.stackoverflow.com/trends?tags=spring-boot%2Cvue.js

I wish to turn these posts to a series called “One Post, One Song”. So here you go: