Anjolaoluwa Adebayo-Oyetoro Maker. Writes sometimes. Playful most times. Loves beautiful UIs.

How to set up your Gridsome app to use TypeScript

4 min read 1163

According to the platform’s official website “Gridsome is a free and open-source static site generator that helps people build websites and apps that are fast, performant, accessible, and search engine optimised by default”.

It is a framework built atop the Vue.js framework (yes, you heard that right. It is a framework of a framework). It leverages on the Vue.js engine to build static websites using GraphQL as a data layer for querying resources imported from data sources. It uses the PRPL architectural pattern to improve the performance of websites.

The PRPL acronym means:

  • Preload — Preload the most important resources
  • Render — Render the initial route as soon as possible
  • Pre-cache — Pre-cache remaining assets
  • Lazy load — Lazy load other routes and non-critical assets

The PRPL pattern is the architectural pattern used for serving Progressive Web Apps (PWAs).

TheGraphQLdatalayer

Gridsome is based on the JAMstack workflow, where all you need is your markup/markdown for static content coupled with JavaScript for functionality and APIs to help do the not-so-easy stuff. It’s greatly influenced by Gatsby.js, a React-based static site generator but built on top of Vue.js, Gridsome is a direct alternative to Gatsby.js.

TypeScript is a typed variation of JavaScript. Typescript helps you write statically typed JavaScript and complies downs to JavaScript at build time (JavaScript on steroids).

Prerequisites

This tutorial assumes the reader has the following:

What is JAMstack?

JAMstack is a collection of best practices, architectural patterns, and workflows that results in building high-speed websites and apps, it prioritizes delivering better performance, higher security, lower cost of use, scalability, and a better developer experience.

“A modern web development architecture based on client-side JavaScript, reusable APIs, and prebuilt Markup”
— Mathias Biilmann (CEO & Co-founder of Netlify)

The JAMstack architecture leverages on pre-rendering files and serving them directly from a CDN, removing the requirement to manage or run web servers. Content updates are pushed through traditional CMS, like WordPress or Drupal and the codebase is managed using a Version Control System, such as Git and deployments are automated using services that offer CI/CD such as Zeit, Netlify, etc.

The JAMstack workflow
The JAMstack workflow credits: https://jamstack.wtf/

How to set up a Gridsome project

To use Gridsome we must first install the Gridsome CLI tool.

This tool helps you bootstrap Gridsome projects on the fly with a default starter.

Installation can be done using Yarn with the following command:

yarn global add @gridsome/cli

Installing the Gridsome package globally gives us access to using the gridsome keyword to perform certain actions.

Next, we create a new project using the create command:

gridsome create gridsome-typscript

This command first clones a customizable starter project from the default starter that contains configuration files needed for bootstrapping your project, then it updates the package.json file and installs the required dependencies for the project.

Now change into the directory for our project using the command:

cd gridsome-typscript

Understanding the Gridsome directory structure

The Gridsome starter project will be structured like this:

# gridsome-typescript

├── gridsome.config.js
├── gridsome.server.js
├── package.json
├── README.md
├── src
│    ├── components
│    │      └── README.md
│    ├── favicon.png
│    ├── layouts
│    │   ├── Default.vue
│    │   └── README.md
│    ├── main.js
│    ├── pages/
│    │   ├── About.vue
│    │   ├── Index.vue
│    │   └── README.md
│    └── templates
│         └── README.md
├── static
│   └── README.md
└── yarn.lock

Lets take time to understand what the files and folder represent and how we can use them.

  • package.json — contains information about your project like which dependencies are installed in your project and scripts that can be run
  • gridsome.config.js — configurations for the site and plugins used and webpack are done here. You can set your website name, metadata, favicon, site description, etc. You can learn more about configuring your website here
  • gridsome.server.js — This file contains configurations for your server. It provides access to use the server API to perform an action such as loading data from either local or external sources, configuring the Express server Gridsome runs during development and creating custom GraphQL schemas
  • /src — this folder houses the majority of the code you’ll write in any project, it contains critical parts of your application such as components, templates, pages, layouts, custom utils, and assets such as stylesheets and images
  • /static — this folder contains static assets that would only need to be accessed once the site is built, such as static pdf files and your robot.txt file. The contents of this folder is copied to the dist directory during build

From .js to .ts

To get started with using Typescript inside our .vue files, we would need to install TypeScript, the TypeScript loader for webpack and the gridsome-typescriptplugin.

yarn add -D typescript ts-loader gridsome-plugin-typescript

Next, we would need to register our gridsome-typescript plugin in the gridsome.config.js file:

plugins: [
  {
    use: 'gridsome-plugin-typescript',
  }
]

Then we create a tsconfig.json file at the base directory of our project and include the following:

{
    "compilerOptions": {
        "target": "es5",
        "module": "es2015",
        "moduleResolution": "node",
        "noImplicitReturns": true,
        "outDir": "./built/",
        "sourceMap": true,
        "strict": true
    },
    "include": [
        "./src/**/*"
    ]
}

This file contains sets of rules and configurations that affect the behavior of TypeScript in our project, The tsconfig.json file specifies the root files and the compiler options required to compile the project.

Create a vue-shims.d.ts in your src folder with the following content:

declare module "*.vue" {
    import Vue from "vue";
    export default Vue;
}

This file helps TypeScript understand the contents of .vue.

Now we can use TypeScript in our .vue files, all that is needed to be done is add to set the language of our script tag in our single-file component to ts:

<script lang="ts">

</script>

Using a pre-made starter

You can also use the gridsome-typescript starter to bootstrap your Gridsome projects. This starter is configured to use typescript and you only need to install it to use it.

This starter makes use of ESLint to enforce certain code practices and rules, it helps report errors and avoid bugs. ESLint help us improve our overall code quality.

To get started with using it, create a new project:

gridsome create gridsome-typescript https://github.com/cleitonper/gridsome-starter-typescript.git

Change the directory into your project folder:

cd gridsome-typescript

Startup your project:

gridsome develop

You should see your app running on http://localhost:8080 after running the gridsome develop command.

Conclusion

In this article we’ve seen how to spin up a Gridsome project and how to integrate TypeScript into it, We’ve also seen what JAMstack is.
To learn more about Gridsome check out their well-detailed documentation. You can visit the Typescript-eslint docs to see how you can configure the pre-made starter, also check out the JAMStack official website and this article to learn more about JAMStack and why you might want to adopt it for your next project.

 



 

Experience your Vue apps exactly how a user does

Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.

Modernize how you debug your Vue apps - .

: Full visibility into your web and mobile apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

.
Anjolaoluwa Adebayo-Oyetoro Maker. Writes sometimes. Playful most times. Loves beautiful UIs.

Leave a Reply