Gatsby.js — Static Assets

John Au-Yeung
3 min readFeb 6, 2021
Photo by Austin Distel on Unsplash

Gatsby is a static web site framework that’s based on React.

We can use it to create static websites from external data sources and more.

In this article, we’ll look at how to create a site with Gatsby.

Importing Assets Directly into Files

We can import images directly into component files.

For example, we can write:

import React from "react"
import laptop from "../images/laptop.jpg"
const IndexPage = () => {
return (
<div>
<img src={laptop} alt="laptop" />
</div >
)
}
export default IndexPage

We import the src/images/laptop.jpg file as a module.

Then we pass that directly as the value of the src prop of our img element.

And it’ll be displayed as an image.

We can also add images with CSS:

src/pages/index.css

.laptop {
background-image: url(../images/laptop.jpg);
height: 200px;
width: 200px;
}

src/pages/index.js

import React from "react"
import './index.css'
const IndexPage = () => {
return (
<div className='laptop'>
</div >
)
}
export default IndexPage

We add the laptop class with the src/images/laptop.jpg set as the background image.

In index.js , we import the CSS and apply the class to the div.

So we’ll see the image displayed as the background image.

Querying for a File in GraphQL Using gatsby-source-filesystem

We can query for a file with GraphQL queries using the gatsby-source-filesystem plugin.

To do this, we write:

gatsby-config.js

module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `src`,
path: `${__dirname}/src/`,
},
},
],
}

src/pages/index.js

import React from "react"
import { useStaticQuery, graphql } from "gatsby"
const IndexPage = ()…

--

--