Use snowpack with vue

Snowpack (https://www.snowpack.dev/) is a new build and packaging tool for Javascript libraries which is proving very handy to build front end applications.

In this article I am going to run through the steps that I took to install snowpack and to get a vue application working using the snowpack tool. All code can be found in my github project at the following link:

https://github.com/muncey/vue-page-render

First run the following commands in a new folder

npm install snowpack
npx snowpack init

Then edit the snowpack.config.js file as follows:

// Snowpack Configuration File
// See all supported options: https://www.snowpack.dev/#configuration

/** @type {import("snowpack").SnowpackUserConfig } */
module.exports = {
  // mount: {},
  // plugins: [],
  // installOptions: {},
  devOptions: {
    port: 3000
  },
  // buildOptions: {},
  alias: {
    'vue': 'vue/dist/vue.esm-bundler.js'
  }
};

Note the port is optional but I am using a codeigniter back end that uses port 8080. The key line is the alias line as that tells snowpack and vue to use the bundle mode which allows you to set up dynamic templates.

Next inside the index.html file I add the following code to read the contents of the #app element and to use the contents of that element as a vue template:

    <script type="module">

        const app2 = document.getElementById('app');
        const appHtml = app2.innerHTML;
        app2.innerHTML = '';

        import { createApp } from "vue";

        const app = createApp({
            template: appHtml,
            data() {
              return {
                items: [{
                  person: 'Jane Cooper'
                }]
              }
            }
        });

        app.mount('#app');

    </script>

I then run npx snowpack dev which spins up a local dev server for me and displays a table using the data from the above Javascript snippet:

If I then go on to change the data inside the Javascript this is reflected in almost real time on the page:

       const app = createApp({
            template: appHtml,
            data() {
              return {
                items: [{
                  person: 'Jane Cooper2'
                }]
              }
            }
        });

Let me know what you think but this to me is a great way to painlessly build up a prototype site or a demonstration using @vuejs (and also @tailwindcss which is for another post).

Leave a comment

Your email address will not be published. Required fields are marked *