22

I would like to add a text file to /src in a way that it always ends up unchanged in the root of the build directory (/public).

In my case specifically I need to add a _redirects file for Netlify to redirect a subdomain to a custom domain.

Running Gatsby 1.0 alpha.

agentofuser
  • 8,987
  • 11
  • 54
  • 85

5 Answers5

32

A bit late to the party.

The easiest way is to add static folder in your project root directory, then place _redirects inside it. Then when you build Gatsby will automatically pick that up and place it within /public folder.

See official docs

csukcc
  • 752
  • 7
  • 8
8

Didn't need to put it in /src. I just added it directly to /public.

Even though it's in .gitignore, I used git add -f /public/_redirects, committed it, and it worked. It doesn't get deleted or overwritten during build.


Another way to do this (which I haven't tested) is to is to copy the file to its destination in /public as part of a post-build script in gatsby-node.js.

agentofuser
  • 8,987
  • 11
  • 54
  • 85
  • Adding it to the post-build script worked. One note is to replace `postBuild` with `onPostBuild`. E.g. as used here: https://spectrum.chat/gatsby-js/general/generating-json-file-with-gatsby~c539d9a7-970c-4a52-ac79-18a51f254537?m=MTUyMzk5NjM1OTk2Nw== – Emil B. Kjer Dec 06 '19 at 09:37
  • This isn't working, trying to send only `index.html` file with inline css style `user-select: none;` embedded, just ran the command `git add -f public/index.html`, pushed to Netlify, and the user can still select. Any hints would be great. – MadHatter Sep 05 '21 at 04:16
1

Gatsby now recommends using the ./static/ directory for files to be copied verbatim into the build destination.

alxndr
  • 3,851
  • 3
  • 34
  • 35
0

Even though this question answered, I found another way to do this and I wanted to share. Just copy your _redirects file or any file during build time, like this:

"build": "gatsby build && cp src/_redirects public/"

and it will copy your file everytime you build for deployment. I hope this helps somebody!

iamdebadipti
  • 161
  • 2
  • 10
0

I solved a similar issue by installing gatsby-plugin-copy-files-enhanced plugin and editing gatsby-config.js like the following:

{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `extra`,
    path: `${__dirname}/src/extra`,
  },
},
{
  resolve: 'gatsby-plugin-copy-files-enhanced',
  options: {
    source: `${__dirname}/src/extra`,
    destination: '/',
    purge: false,
  },
},

Note: Don't forget to move your _redirects file to src/extra.

Igor de Lorenzi
  • 573
  • 1
  • 7
  • 18