Thursday, October 6, 2022

gatsby copy files as last step of build

My employer has the same site in different locales, served by one main Gatsby-powered project. 

We wanted to have a different "robots.txt" for each process.... our gatsby-config.js had something that LOOKED like it was copying robots.txt in particular, but our use of gatsby-plugin-copy-files wasn't actually doing anything... it was confusing because the file still seemed to be copied, but apparently as part of a general "copy from static/ to public/" function - and overall it was hard to track what Gatsby was doing when.

I didn't do a deep dive into Gatsby, but this github entry seemed to be covering similar ground... the secret was to make a gatsby-node.js, and then do this:

const path = require('path');
const fs = require('fs-extra');

const envLocale = process.env.GATSBY_LOCALE || 'en-us';

/**
 *  Copy a locale-specific robots.txt file into place
 **/

exports.onPostBuild = () => {
  const src = path.join(
    __dirname,
    `/src/content/robots/${envLocale}/robots.txt`,
  );
  const dest = path.join(__dirname, `/public/robots.txt`);
  fs.copySync(src, dest);
};

It always feels fraught banging on tech someone else put into place, and you've never done a "hello world" with or anything. And gatsby is "interesting" especially in developer mode, where its often copying files over. But this seems to get the job done.

No comments:

Post a Comment