Importing Assets Directly into Files
There are two major ways to import assets, such as images, fonts, and files, into a Gatsby site. The default path is to import the file directly into a Gatsby template, page, or component. The alternative path, which makes sense for some edge cases, is to use the static folder.
Importing assets with webpack
With webpack you can
src attribute of an image or the
href of a link to a PDF.
To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a
data URI instead of a path. This applies to the following file extensions:
Here’s an example:
This ensures that when the project is built, webpack will correctly move the images into the public folder, and provide us with correct paths.
You can reference files in CSS to import them, too:
webpack finds all relative module references in CSS (they start with
If you’re using SCSS the imports are relative to the entry SCSS file.
Please be advised that this is also a custom feature of webpack.
Video hosted on egghead.io.
- More on using an imported font.
Querying for a
File in GraphQL using gatsby-source-filesystem
You can also import files using GraphQL by querying for them in your data layer, which will trigger copying of those files to the public directory. Querying for the
publicURL field of
- Copy all
Reference those PDF files in a page with useStaticQuery:
- Link to attachments in the frontmatter of your Markdown files:
In an article template component file, you can then query for the attachments:
Read more about querying for files in