Ed Weymouth - Big Nerd Ranch Tue, 19 Oct 2021 17:47:12 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 Completing the CircleCI https://bignerdranch.com/blog/completing-the-circleci/ Wed, 19 Feb 2020 13:58:43 +0000 https://nerdranchighq.wpengine.com/?p=4126 Test automation and continous integration can streamline your workflow processes. Thankfully, cloud and SaaS solutions have turned a bare metal headache into a configuration file and a few command line tools. CircleCI is one of these solutions, but it takes some debugging and tinkering to get it running. Let's explore.

The post Completing the CircleCI appeared first on Big Nerd Ranch.

]]>
It’s nice to have the sense of security and confidence in your code that testing can provide, but running tests manually before every push can feel like a real chore. Thankfully there are some very handy cloud-based SaaS solutions that can outsource this repetitive task.

The solution we’ll be working with is CircleCI. If you are unfamiliar with continuous integration and deployment, take a look at Lev Lazinskiy’s explanation.

Before We Start

Get or Make the App

This repository has some starter code. Alternately, you can install vue-cli and set up a new project. After running create, remember to choose:

Cool. You should be good to go. Take a minute to cd into your new app and spin up the local dev server, run the tests and familiarize yourself with it. While you are there check that you have a config file on the right path. If you don’t, add it:

$ touch .circleci/config.yml

Link Everything Up

Sign in to your CircleCI account and navigate to the add projects tab. Search for your Vue Hello World repo and select add project.Preflight checklist done. Let’s set up our CI/CD.

 

CircleCI Configuration

Orbs and Workflows

Orbs are certified or third party configurations that streamline an action while simultaneously allowing you to access the underlying configuration options. We are going to use two orbs. The Heroku orb and the Cypress orb. The Heroku orb is in CircleCI’s registry. For the Cypress orb to work correctly, you’ll need to change security settings in CircleCI to allow for uncertified and third-party orbs.

Workflows are a collection of jobs run in parallel or sequence. We’ll define those as we build our configuration file.

Config Setup, Simple

Orbs are only available in version 2.1 of CircleCI, so we need to specify that version on the first line of our config file. After that CircleCI is going to be looking for some defaults. Let’s add those in as well.

# .circle/config.yml
version: 2.1
jobs:
  build:
    docker: 
      - image: circleci/node:12 # the primary container, where your job's commands are run
    steps:
      - checkout # check out the code in the project directory
      - run: echo "hello world" # print a message to verify action

workflows:
  test_then_build:
    jobs:
      - build

As we begin to add lines to our yaml we can use our command line tool to validate and confirm steps incrementally.

$ circleci run validate
Config file at .circle/config.yml is valid.

Then you can pack it up and push it to GitHub. The build won’t take too long for this one. Take a look at the logs in CircleCI. You should see your echo run in the console:Adding Orbs

 

We could build out each step in turn by picking the container, establishing each process and testing it, but we have orbs! Someone has already done that for us. Let’s scratch some of that original file and add our e2e test runner.

# .circle/config.yml
version: 2.1
- jobs:
-   build:
-     docker: 
-       - image: circleci/node:12 # the primary container, where your job's commands are run
-     steps:
-       - checkout # check out the code in the project directory
-       - run: echo "hello world" # print a message to verify action
+ orbs:
+   cypress: cypress-io/cypress@1 # Versions are changing a lot, leave off specifics to get the latest

workflows:
  test_then_build:
    jobs:
-     - build
+     - cypress/run:
+         start: npm run serve # We need our server running
+         wait-on: 'http://localhost:8080'
```

**Wait!** before you push that...  `cypress/run` is going to run our tests inside the container and needs some direction to find its way.  Let's add a `baseUrl` to `./cypress.json`

```javascript
{
  "pluginsFile": "tests/e2e/plugins/index.js",
  "baseUrl": "http://localhost:8080"
}

Wait! before you push that… cypress/run is going to run our tests inside the container and needs some direction to find its way. Let’s add a baseUrl to ./cypress.json

{
  "pluginsFile": "tests/e2e/plugins/index.js",
  "baseUrl": "http://localhost:8080"
}

Now, when our container spins up and runs Cypress, instead of looking for local files it will look for a base url and run our e2e tests. Add it, commit it and open up your workflows panel in CircleCI.Passed, with flying colors. Now let’s add the next step:

 

version: 2.1
orbs:
  cypress: cypress-io/cypress@1 
+ heroku: circleci/heroku@0 # Heroku orb for deployment

workflows:
  test_then_build:
    jobs:
      - cypress/run:
          start: npm run serve # We need our server running
          wait-on: 'http://localhost:8080'
+     - heroku/deploy-via-git:
+          requires: # Makes the above command wait until the required command is complete
+            - cypress/run

Reading down to the jobs section of the Heroku orb at the deploy-via-git command you’ll see that CircleCI needs an API key and an app name to complete its remote URI. We can set those up in our project env vars.

Push it to GitHub and watch it build:Now as you start to build tests and code CircleCI will check all your tests and only deploy if your tests pass. From here you can customize even further. Some options you can experiment with are adding unit tests, running them in parallel, deploying different branches or deploying to different hosting services. There are a lot of possibilities. Take some time and keep exploring.

 

The post Completing the CircleCI appeared first on Big Nerd Ranch.

]]>
Jazzing It Up With Gatsby https://bignerdranch.com/blog/jazzing-it-up-with-gatsby/ Mon, 14 Oct 2019 18:44:55 +0000 https://nerdranchighq.wpengine.com/?p=3872 The Roaring Twenties: a time to remember, building a static site with Gatsby.js that has absoluting nothing to do with F. Scott Fitzgerald, Jay Gatsby or the Twenties. Our static site can fix that... with the help of Netlify's lambda functions and some static site plugins, we'll have a little tribute page up and running in no time.

The post Jazzing It Up With Gatsby appeared first on Big Nerd Ranch.

]]>
Welcome

Today we are going to talk a bit about Gatsby.js and Netlify, what they are, and how they can be used.

Chances are you’ve probably heard about Gatsby.js. If you haven’t, here is a quick definition of Gatsby.js from their site:

Gatsby is a free and open source framework based on React that generates some truly righteous static sites with the added benefit of a plethora of plugins and starters.

The documentation is nicely written, well sourced, and communicates clearly: We are here to help. Of course — as with every framework, library, or otherwise categorized collection of code — there are always pitfalls, but the overall feeling of the framework itself suggests an ease of use and clearly defines well-handled abstractions.

As a nice, compact experiment to explore these new concepts, let’s build a tribute site to the roaring twenties with our new site generator.

Start It Up

With the assumption that you have already acquired some knowledge and have installed npm and subsequently yarn, we will begin. The gatsby documentation recommends a global installation of their CLI. The command line interface: gatsby-cli, provides a bunch of useful commands that help make development smoother. Open your terminal and run this command:

$ yarn global add gatsby-cli

Or if you prefer npm:

$ npm install gatsby-cli --global

Success! We now have the tool needed to create our tribute site. Let’s create it.

$ gatsby new tribute
$ cd tribute
$ gatsby develop

There it is, your new site, and it’s set up to establish good practices for loading static assets quickly and efficiently. It also has a GraphQL instance running in the background that lets you query your directory source tree, markdown pages and a host of other options. We’ll dig into our simple use case for querying the source tree later. For now, open the code in your favorite code editor, and check out the rendered front-end at localhost:8000. You should see this:

Make a change, some text to start. You’ll notice that hot reloading refreshes your changes for you. Having a development environment is great, but the real question might be: where is production going?

Production

For our production environment, we are going to set up a GitHub repo and link that GitHub repo to Netlify. Gatsby.js thoughtfully includes a .gitignore in its default starter. Open up a new tab on GitHub, and create a new repository.

Gatsby also starts you out with a .git folder to track changes, so no need to git init. Just grab your new repo’s URL, and add the remote origin, package up your changes, and push to master.

$ git remote add origin <new_repo_url>  
$ git add -A 
$ git commit -m 'default gatsby boilerplate'
$ git push -u origin master

Wire It Up

Next step for production is to link your Gatsby.js site repository to Netlify. If you are looking for more dynamism, you may want to consider your options carefully before moving forward with Netlify. For now the ask is minimal and well defined: a simple static tribute site.

Step one: Make a Netlify account. Once that’s finished, make a new project. You should start out on the overview page. Underneath the header that announces your team and project name, there is some tab navigation:

Inside that navigation, click on Deploys -> Deploy Settings -> Link Site To Git and link up your GitHub account to Netlify. You are looking for a button like this:

Choosing one of these options should allow you to search for a repository.

You might need to configure the Netlify app on GitHub if you haven’t already set up Netlify permissions. Netlify provides a link in the repository search screen. Find your repo, and select it to attach to the Netlify instance. Once attached, you should see a screen like this:

These are the defaults settings for Netlify. It means that your deployment hook, the action that listens for repo changes to rebuild your code, is attached to the master branch. The script that is run when master is updated is going to be gatsby build, and the publish directory is going to be public.

Unless you have some custom settings, and given the static site nature of this build environment one would hope that isn’t the case, this setup should get you rolling.

Let’s get the deployment set, and then have some fun with the code. We already pushed to master, so no sense in doing it again. Instead, let’s manually trigger a rebuild from the Deploys submenu:

Watch those logs for site is live, then go to the remote path attached to your Netlify instance. You should see our default starter page up and running, purple astronaut and all.

Time to Try Out Gatsby.js

At this point you might be chomping at the proverbial bit, wanting to get in there and really build something. Now is your time.

We are going to leverage some of fun, new libraries in our framework. The first one to explore out of the gate is the image service that Gatsby.js provides. It’s nicely compact, and will allow us to throw a hero image in there fairly quickly. Eventually, we will want to build more than one hero image onto our new page, so let’s gather a GraphQL fragment together:

import { useStaticQuery, graphql } from "gatsby"
...
export const heroQuery = graphql`
  fragment heroQuery on File {
    childImageSharp {
      fluid( maxWidth: 1240 ) {
        ...GatsbyImageSharpFluid
      }
    }
  }
`

This is a standard GraphQL fragment, a reusable section of a query. It’s running against our GraphQL instance and is aware of the file tree. We’ll give it the name heroQuery, and tell it that it’s going to search against the File node.

The image library provides us with a fade-in effect to lazy-load images. We could use the standard ...GatsbyImageSharpFluid, however we have some more options. Appending the _tracedSVG provides a very nice fade-in effect that traces the outline of the image as it lazy loads. It’s interesting for the viewer, and it helps with performance. Many thanks to Kyle Gill for the example ????.

export const heroQuery = graphql`
  fragment heroQuery on File {
    childImageSharp {
      sizes( maxWidth: 1240 ) {
        ...GatsbyImageSharpSizes_tracedSVG
      }
    }
  }
`

It may be useful to note that GatsbyImageSharpSizes won’t work without gatsby-transformer-sharp and gatsby-plugin-sharp. These libraries are generally packaged standard with our default loadout, but if you don’t see them you can run:

$ yarn add gatsby-transformer-sharp gatsby-plugin-sharp

Then, add them to your gatsby-config.js. This allows you to directly access and set the options and transformers for the sharp image nodes library in Gatsby.js

module.exports = {
  plugins: [
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
  ]
}

Let’s take this fragment and add it to our boilerplate image component. If you are wondering where that file is, check: ./src/components/. This setup is pretty basic, we are using this GraphQL query and our hero fragment to look through our files and find our image.

import { useStaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"

export const HeroImage = () => {
  const data = useStaticQuery(graphql`
    query {
      main: file(relativePath: { eq: "some-pic1.jpg" }) {
        ...heroQuery
      },
    }
  `)

  return <Img 
    title="The Roaring Twenties in Image Form"
    alt="Some awesome twenties stuff happening"
    sizes={data.main.childImageSharp.sizes}
  />
}

These queries operate through the GraphQL instance and are aware of the file path through the plugin attached in the gatsby-config.js.

{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `images`,
    path: `${__dirname}/src/images`,
  },
},

All pretty cool stuff. At this point I’m gonna do some hand waving (feel free to do your own dev magic) ????, get a few fonts and throw a bit of css in there ????, to round things off ????. With all our new code in place, we package it up, push to master, and Netlify swings into action.

Deployed in a single push and production is golden, just like the age. If you liked this or found it helpful be sure to give us a shout. If you’re interested in the code base, check it out here.

The post Jazzing It Up With Gatsby appeared first on Big Nerd Ranch.

]]>