Gatsby: How to Change 'gatsby build' directory?

Created on 24 Oct 2019  ·  6Comments  ·  Source: gatsbyjs/gatsby

How to Change 'gatsby build' directory?

question or discussion

Most helpful comment

Yes, you can.
To change the folder from public to dist, add the following code in your gatsby-node.js:

const path = require("path")
const fs = require("fs")

exports.onPreInit = () => {
  if (process.argv[2] === "build") {
    fs.rmdirSync(path.join(__dirname, "dist"), { recursive: true })
    fs.renameSync(
      path.join(__dirname, "public"),
      path.join(__dirname, "public_dev")
    )
  }
}

exports.onPostBuild = () => {
  fs.renameSync(path.join(__dirname, "public"), path.join(__dirname, "dist"))
  fs.renameSync(
    path.join(__dirname, "public_dev"),
    path.join(__dirname, "public")
  )
}

All 6 comments

So when gatsby build runs, it will output all the files you need to deploy to the public folder inside the root of the site folder. That said, after the site is built, you could just take the contents of such and move it into another directory completely.

@PiccoloYu We currently don't support a configurable output directory and don't plan to doing so in the near future.

Let's follow along the conversation in https://github.com/gatsbyjs/gatsby/issues/1878

Closing this

Yes, you can.
To change the folder from public to dist, add the following code in your gatsby-node.js:

const path = require("path")
const fs = require("fs")

exports.onPreInit = () => {
  if (process.argv[2] === "build") {
    fs.rmdirSync(path.join(__dirname, "dist"), { recursive: true })
    fs.renameSync(
      path.join(__dirname, "public"),
      path.join(__dirname, "public_dev")
    )
  }
}

exports.onPostBuild = () => {
  fs.renameSync(path.join(__dirname, "public"), path.join(__dirname, "dist"))
  fs.renameSync(
    path.join(__dirname, "public_dev"),
    path.join(__dirname, "public")
  )
}

Your solution works for me @abraaoz.
Thank you very much.

based on abraaoz y resolve like this

const path = require("path")
const fs = require("fs-extra")

exports.onPostBuild = () => {
fs.copySync(path.join(__dirname, "public"), path.join(__dirname, "../public"),{ overwrite: true })

}

@abraaoz's solution works great. However, gatsby serve now fails because it tries to serve the build from the /public directory.

Is there a way to override this as well? The docs don't seem to provide an option to serve a specific path.

Was this page helpful?
0 / 5 - 0 ratings