Skip to content
Please

Moving to Gatsby

Life, Programming, Gatsby1 min read

My friend Momoko is building a new website and she wanted some help from me to create a kind of interactive map. As part of this I thought it might be simpler and cheaper to just build the site using Gatsby JS instead of Squarespace. To test this idea out I created a test site to see how hard it would be to create a simple website with a map and some content.

Gatsby JS is pretty slick. I was genuinely surprised how easy it was to build and test a simple website. Gatsby has a pretty extensive set of plugins and it is easy to update. Some specific things I like are

  • Developing and setting up this blog was really easy
  • It was not hard for me to create a small script to publish the site S3
  • It has built in support for running as a progressive web app
  • A lot of pre-made themes
  • Support for Contentful

After finishing my short prototype for Momoko I decided to recreate my blog using Gatsby. The migration itself wasn't too hard. My site was already a static website but using a different framework. I simply had to find a theme I liked and then copied over my markdown posts. I couldn't seem to get the gatsby-plugin-s3 so I created my own script to upload files.

At some point I will update this script to handle only uploading the diff.

1import S3 from 'aws-sdk/clients/s3';
2import * as fs from 'fs';
3import * as path from 'path';
4import * as mime from 'mime-types';
5
6const s3Client = new S3({
7 apiVersion: '2006-03-01',
8 region: 'us-east-1'
9});
10
11const uploadDir = (folder: string, directory: string) => {
12 // get of list of files from 'dist' directory
13 fs.readdir(folder, (err, files) => {
14 if (!files || files.length === 0) {
15 console.log(`Folder [${folder}] is empty or does not exist.`);
16 return;
17 }
18
19 // for each file in the directory
20 for (const fileName of files) {
21
22 // get the full path of the file
23 const filePath = path.join(folder, fileName);
24
25 // Recursively process directories
26 if (fs.lstatSync(filePath).isDirectory()) {
27 const nestedDirectory = directory === '' ? fileName : `${directory}/${fileName}`;
28 uploadDir(filePath, nestedDirectory);
29 continue;
30 }
31
32 // read file contents
33 fs.readFile(filePath, (error, fileContent) => {
34 // if unable to read file contents, throw exception
35 if (error) { throw error; }
36
37 const contentType = mime.lookup(filePath);
38 const key = directory === '' ? fileName : `${directory}/${fileName}`;
39
40 // upload file to S3
41 s3Client.putObject({
42 Bucket: process.env.S3_BUCKET,
43 Key: key,
44 Body: fileContent,
45 ContentType: contentType
46 }, (res) => {
47 console.log(`Successfully uploaded '${key}'!`);
48 });
49 });
50 }
51 });
52};
53
54// resolve full folder path
55const publicFolderPath = path.join(__dirname, '../public');
56uploadDir(publicFolderPath, '');