DEV Community

Cover image for Modern WebApps - Infrastructure: Vue, Parcel & Workbox
Thomas Sarmis
Thomas Sarmis

Posted on • Updated on • Originally published at greekdeveloper.com

Modern WebApps - Infrastructure: Vue, Parcel & Workbox

Single Page Applications (SPA) are web applications that are contained in a single web page, providing a seamless navigation experience due to not having to download and parse the html for each page. Progressive Web Applications (PWA) are web applications that, using a service worker "proxy" and a manifest file, provide the necessary infrastructure to allow cashing of the application by the browser in order to be usable in poor, or no-network conditions. All modern browsers and OSes allow PWAs to be "installed" locally and, thus, provide for a native-like user experience.

A PWA is often a viable alternative to building a native application, especially for small teams, since most app stores now accept PWAs and all major OSes (Windows, Android, iOS) allow PWAs to be installed and appear on the desktop. PWAs open instantly and the browser can be directed to hide it's controls providing a native-like look and feel.

Modern tooling can simplify development but setting it up can be a time-consuming task. Let's see how to setup a SPA & PWA project. The scope of this tutorial is to describe the setup and not each framework/tools specifically - Each of these tools has extended documentation that explains how each works.


Framework & Tools

Vue.js

We will use the Vue ecosystem for the heavylifting:

  • Vue.js will handle our views by providing a declarative approach in defining them and seperating the code in single-file-components,
  • VueX will be used for state management
  • Vue Router will be used to handle the SPA routes

Node.js

node.js will provide support for the bundling utilities and all other utilities that might be required

Parcel.js

Parcel bundler will be used to build and bundle the application

Workbox

Workbox will handle the service-worker details.


Files layout

  • ./src will contain all source code for this project.
    • ./src/web will contain the source code for the web application (the html client).
    • ./src/db (optional) will contain any database initialization scripts
    • ./src/server (optional) will contain any server-side projects
  • ./dist will contain all generated artifacts and should be ignored in git
    • ./dist/web will contain the builded and bundled web application.
    • ./dist/db (optional) will contain any artifacts generated by the database scrits
    • ./dist/server(optional) will contain any server-side projects (compiled)
  • ./.cache will be generated by parcel and should be ignored in git
  • ./node_modules will be generated by npm or parcel and should be ingored in git

The code

The code can be found in project's github repo

Javascript dependencies

Entry point (index.html)

./src/web/index.html is our entry point and just links everything together

  • <link rel="manifest" href="./manifest.webmanifest"> links the .webmanifest file
  • <div id="vueapp"></div> defines vue mounting point
  • <script src="./index.js"></script> loads the script that contains the vue application
  • navigator.serviceWorker.register('/service-worker.js'); registers the service worker script
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="manifest" href="./manifest.webmanifest">

        <title>Vue.js Single Page Application Template</title>       
    </head>

    <body>
        <div id="vueapp"></div>          

        <script src="./index.js"></script>
        <script>
            if ('serviceWorker' in navigator) {
                window.addEventListener('load', () => {
                    navigator.serviceWorker.register('/service-worker.js');
                });
            }            
        </script>
    </body>
</html>

Manifest

./src/web/manifest.webmanifest describes the application and is required for the application to be considered a PWA.
It's important to maintain the .webmanifest extension for parcel compatibility.

{
    "name": "My application name",  
    "short_name": "app",

    "start_url": "/",
    "background_color": "#3367D6",
    "display": "standalone",
    "scope": "/",
    "theme_color": "#3367D6",

    "icons": [
        {
            "src": "/res/app-256.png",
            "type": "image/png",
            "sizes": "256x256"
        }
    ]
}

Service Worker (Workbox)

./src/web/service-worker.js implements the service worker that is requred for considering the application to be a PWA. Google's workbox is used. Workbox defines multiple stategies (network-first, cache-first, and Stale-while-revalidate). In this example all resources are served using the network-first strategy since this is the most responsice approach and maintains the capability to work offline.

console.log("service-worker.js")
// import service worker script
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.2.0/workbox-sw.js');

// Network First
[ 
    '/$',  // Index 
    '/*',  // Anything in the same host
    '.+/*' // Anything in any host 
]
.forEach(mask => {
    workbox.routing.registerRoute(
        new RegExp(mask),
        new workbox.strategies.NetworkFirst( { cacheName: 'dynamic' } ) 
    );
});

Vue binding

./src/web/index.js is used to bind the vue application and our css (in scss). It imports the Vue framework, our vue application code (app.vue) and our styles (styles.scss) - All these files are located in ./src/web/ but we are using relative paths in the imports. Finally we mount our vue application to the corresponding div element.

import Vue from 'vue';

import App from './app.vue';
import './style.scss'

new Vue(App).$mount('#vueapp')

Vue Application

./src/web/app.vue contains our vue application as a single file component.

In the <template> we construct a simple navigational menu and the router-view which is the host for our single page application, all other pages are mounted in the router-view element. In this template we are using pug insteand of html.

In the <script> we import the vue framework and two custom modules, the _router.js and the _store.js and we create our vue application by extending the default vue application with the store and router modules we just loaded.

In the <style> we providing some local (scoped) styling for the menu using scss (which out bundler will convert to css)

<template lang="pug">
    div
        nav.navbar
            router-link(to="/") home
            router-link(to="/profile") profile
            router-link(to="/about") about
        router-view
</template>


<script>
    import Vue from "vue";
    import {router} from './_router.js';
    import {store} from './_store.js'

    export default Vue.extend({ 
        store: store,
        router: router    
    });    
</script>


<style lang="scss" scoped>

    .navbar {
        text-align: center;

        * + * {
            margin-left: 8px;
        }
    }
</style>

Router

./src/web/_router.js configures and initializes vue-router by loading all pages and declaring their routes.

import Vue from "vue";

import VueRouter from 'vue-router';

Vue.use(VueRouter)

// 1. Import Components
import home    from './vues/home.vue'
import about   from './vues/about.vue'
import profile from './vues/profile.vue'

// 2. Define some routes
const routes = [
    { path: '/'       , component: home    },   
    { path: '/profile', component: profile },
    { path: '/about'  , component: about   }
]

// 3. Create & Export the router 
export const router = new VueRouter({
    routes: routes
})

Store

./src/web/_store.js configures and initializes the vuex store module. It declares the global state and the available mutations. The vuex allows for global state to be modified by all view components (through the mutations) while mainting the reactivity of the framework. (ie commiting a mutation will update all components that are affected by the state change).

import Vue from 'vue'
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        name: 'Unknown'
    },

    // Usege: $store.commit('mutationan', parameter)
    mutations: {
        setName(state, name) {
            Vue.set(state, 'name', name);
        }
    }
});

Pages

We have three pages in our example, home and about are almost identical, both are rendering the name property of the store.

profile provides an input box where the user an type his name and instantly updates the global state when the value of the input changes.

./src/web/vues/about.vue

<template lang="pug">
    div 
        h1 About
        p  Welcome: {{$store.state.name}}
</template>

<script>
    export default {

    }
</script>

./src/web/vues/home.vue

<template>
    <div> 
        <h1>Home</h1> 
        <p> Welcome: {{$store.state.name}}</p>

    </div>   
</template>


<script>
    export default {
    }
</script>

./src/web/profile.vue

<template lang="pug">
  div 
    h1 Profile
    p  Welcome: {{$store.state.name}}
    div.form 
      table
        tr
          td Name
          td
            input(:value="$store.state.name" @input="$store.commit('setName',$event.target.value)")
</template>

<script>
    export default {

    }
</script>
<style lang="scss" scoped>
    .form {
        display: flex;
        justify-content: center;
    }
</style>

Developing

The following steps are required in order to develop on this template

  • Download or clone the code

  • Install parcel npm i -g parcel-bundler

  • Install project dependencies npm install (in project root)

  • Run the dev script npm run dev

Original post at greek developer

Top comments (8)

Collapse
 
johnson_cor profile image
Corey Johnson • Edited

Great post! Can't wait to try it out

Edit: I tried running your sample but get an error..

sh: start: command not found
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! greekdev-template-vue-spa@1.0.0 dev: `start parcel src/web/index.html --no-hmr --out-dir ./dist/web`
npm ERR! spawn ENOENT
npm ERR! 
npm ERR! Failed at the greekdev-template-vue-spa@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Collapse
 
sarmis profile image
Thomas Sarmis • Edited

Oups. I will push a fix tomorrow, but you can fix it locally by removing the start command from the dev script in package.json

Correct is

"scripts": {
    "dev": "parcel src/web/index.html --no-hmr --out-dir ./dist/web"
},
Collapse
 
johnson_cor profile image
Corey Johnson

Thanks!

Thread Thread
 
sarmis profile image
Thomas Sarmis

I upload the fix and editited my previous reply... thank you for your patience

Collapse
 
filipefox profile image
Filipe Martins
Collapse
 
sarmis profile image
Thomas Sarmis

Yes it's a great tool, and perhaps it automates all this, but I think that by linking all the parts manually you gain some insight in the process

Collapse
 
hksduhksdu profile image
hksduhksdu

Thank you for the tutorial. For the workbox script, when you have "+/", why do you still need the first two "/$" and "/"?

Collapse
 
sarmis profile image
Thomas Sarmis

You are correct, they are redundant, but I decided to leave them there as place holders for when the /+ gets moved to another policy or gets broken down to more detailed routes by anyone who will use this example