Snipcart Integration with Webpack Powered Spike

It is time once again to show you how to easily integrate our shopping cart platform Snipcart into your projects. In this tutorial we'll play with the awesome static website generator that is Spike. It has been developed by the guys behind a lot of really nice web projects at Carrot Creative, so it's worth taking a look!

Let's get started with the ecommerce integration. If flexibility is what you’re after, then you’ll find yourself very pleased with a Spike + Snipcart combination for your online store.

For this tutorial, all you need is a Snipcart account (free in test mode). That’s it, that’s all!

How’s that? It’s because Spike is based on a simple ideology: "Out of the box, Spike will just take standard html, css, and js files and copy them over without any modification. It is up to you to build your ideal system out of plugins that transform your content."

In other words, it's a thin layer that leverages different "ecosystems" such as webpack, to bundle and generate a static website. You’re the one in charge of defining the build process. Luckily enough, Spike makes the whole process feel quite natural. This way, you can easily start with a beginner build without having to worry about losing any extensibility that might be required if you were to complexify your integration.

Now let’s get started. First, you’ll have to install Spike with the following command: npm install -g spike.

Next, you can use Spike's default template for our project using the following scaffolding command: spike new spike-snipcart.

If you plan on building and deploying your website on a VM, you’re also going to have to add Spike as a dependency with npm install --save spike.

1. Declaring the products

Before we can move forward, we’re going to create our products. For this demo, we’ll keep it simple and won't be using any external data. That being said, we still don’t want to input it directly into our views. To achieve this, we’ll create a data folder within our assets folder. From there, we’ll declare a new folder called products with the index.js file containing the following:

module.exports = [
    {    
        name: 'The Revolver',
        price: 15,
        description: 'Easy to carry, perfect while roaming.',
        sku: '1',
        image: 'https://snipcart.com/media/10191/nerf-1.jpg'
    },
    {    
        name: 'The Heavy Duty',
        price: 65,
        description: 'Spray and pray.',
        sku: '2',
        image: 'https://snipcart.com/media/10192/nerf-2.jpg'
    },
    {    
        name: 'The One Hit Wonder',
        price: 70,
        description: 'One shot, one opportunity',
        sku: '3',
        image: 'https://snipcart.com/media/10193/nerf-3.jpg'
    }
]

2. Tweaking our app.js

Now that we have the data, we’re going to have to inject it into our pages so that we can actually use it. To do this, we’ll have to go to our app.js file and use the following declaration to load it: const products = require('./assets/data/products/index.js')

Then, we’re going to use the following reshape declaration to inject our products into the locals variable, just like this:

reshape: htmlStandards({
  locals: (ctx) => { return { products: products } }
})

3. Creating our views

Now that we’ve got access to products in our views, let's use it! To keep this demo simple, we’ll wipe out the default index.sgr page and create a new one, which we’ll use to display our products instead.

This is what it’ll look like:

extends(src='layout.sgr')
  block(name='content')
    div(class='columns')
      each(loop='product of products')
        div(class="column")

          img(src="{{ product.image }}" alt="{{ product.name }}" class="thumbnail product_image")
          div(class="title") {{ product.name }}

          button(class="snipcart-add-item"
            data-item-name="{{ product.name }}"
            data-item-id="{{ product.sku }}"
            data-item-image="{{ product.image }}"
            data-item-description="{{ product.description }}"
            data-item-url="/"
            data-item-price="{{ product.price }}") Buy it for {{ product.price }} $

You see, each product is iterated and a buy button is created for each and every one of them. Now, we’re only missing the necessary scripts for Snipcart, which we’ll add right into our layout. Note, that if you were to have multiple pages, we recommend you use an include to do so.

Here's our new layout:

doctype html
html
  head
    block(name='meta')
      meta(charset='utf-8')
      meta(http-equiv='X-UA-Compatible' content='IE=edge')
      meta(name='description' content='')
      meta(name='author' content='maximelaboisson')
      meta(name='viewport' content='width=device-width, initial-scale=1')

    block(name='title')
      title Spike & Snipcart e-commerce powered demo store

    block(name='stylesheets')
      link(rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.1/css/bulma.min.css')
      link(rel='stylesheet' href='css/index.css')
      link(href="https://cdn.snipcart.com/themes/2.0/base/snipcart.min.css" rel="stylesheet" type="text/css")

  body

    div(class='header title')
      | Spike & Snipcart e-commerce powered demo store

    main(role='main' id='{{ pageId }}')
      block(name='content')

    block(name='javascript')
      script(src='js/main.js' defer)
      script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js')
      script(src="https://cdn.snipcart.com/scripts/2.0/snipcart.js" data-api-key="{{ APIkey }}" id="snipcart")

Notice how we entered our Snipcart API key as follows: {{ APIkey }}. For it to work, we’ll have to inject it into our locals using the same process we just used for the products.

To do this, head on back into your app.js file and change the reshape declaration to:

reshape: htmlStandards({
   locals: (ctx) => { return { products: products, APIkey: 'YOUR_API_KEY' } }
 })

4. Booting up our website

Let's see how it looks now! Using the Spike CLI, use the following method: spike watch in your project folder. It’ll create a neat dev server that will serve your public build folder and won’t reload all code changes. Now, if you hit the website, this is what you should see.

5. Deploying

Now that that’s all done, we’ll use Netlify to deploy our site. You’ll see it’s pretty straightforward. Simply push your project to a Git repo and then hit up Netlify's website. From there, use spike compile as your build command, and public as your publishing directory. That’s all! Netlify will take charge of the rest! Take a look at our example. This is what it should look like:

There you have it! Your website should be working as it was locally!

It took me an hour or so to put this demo together. Although Spike has a good doc repertoire, I still had to do some extra digging to find some good examples for this demo. Fortunately, there’s an Open Source website that was created using Spike, which offers a wide variety of solid examples.

Have a look for yourself: https://spike.readme.io/docs/built-with-spike

At the end of the day, I feel as though Spike is really powerful, which is awesome! But, it does take some getting used to if you really want to make the most of it. For example, I could have fetched some external data for the product build process, but I held back for the purpose of this demo. It’s something that I do plan on exploring in the future, though. It should be interesting. I’ll definitely keep you guys posted once I’ve given it a go! Feel free to fork the code on Github.

Suggested posts: