Ecosystem

Design

Adding Images, Fonts, and Files

With Webpack you can import a file right in a JavaScript module. This
tells Webpack to include that file in the bundle. Unlike CSS imports, importing
a file gives you a string value. This value is the final path you can reference
in your code, e.g. as the 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: svg, jpg,
jpeg, png, gif, mp4, webm, wav, mp3, m4a, aac, and oga.

This ensures that when the project is built, Webpack will correctly move the
images into the public folder, and provide us with correct paths.

This works in CSS too:

.Logo{background-image:url(./logo.png);}

Webpack finds all relative module references in CSS (they start with ./) and
replaces them with the final paths from the compiled bundle. If you make a typo
or accidentally delete an important file, you will see a compilation error, just
like when you import a non-existent JavaScript module. The final filenames in
the compiled bundle are generated by Webpack from content hashes. If the file
content changes in the future, Webpack will give it a different name in
production so you don’t need to worry about long-term caching of assets.

Please be advised that this is also a custom feature of Webpack.

Two alternative ways of handling static assets are described in the next sections.

Query for File in GraphQL queries using gatsby-source-filesystem

You can query the publicURL field of File nodes found in your data layer to trigger copying those files to the public directory and get URLs to them.

Examples:

Copy all .pdf files you have in your data layer to your build directory and return URLs to them:

import{ withPrefix }from'gatsby-link'render(){// Note: this is an escape hatch and should be used sparingly!// Normally we recommend using `import` for getting asset URLs// as described in “Adding Images and Fonts” above this section.return<img src={withPrefix('/img/logo.png')} alt="Logo"/>;}

Keep in mind the downsides of this approach:

None of the files in static folder get post-processed or minified.

Missing files will not be called at compilation time, and will cause 404
errors for your users.

Result filenames won’t include content hashes so you’ll need to add query
arguments or rename them every time they change.

When to Use the static Folder

Normally we recommend importing stylesheets,
images, and fonts from JavaScript. The static
folder is useful as a workaround for a number of less common cases: