The Gatsby docs for path prefix show I can define something like pathPrefix: "/blog"
, and indeed I tried it and it just worked. However, I'd rather not hardcode the path where the app will live. I'd like to be able to deploy the build to multiple paths and have it just work from all of them. I'm hoping there's a way I can make the build work from any arbitrary path. Is there?
Gatsby pathPrefix without hardcoding
Asked Answered
You can use gatsby-link to help you with that. It functions like React-Router's Link
component, but helps you out with path prefixing. For example, if you set your pathPrefix: "/myBlog"
...
import Link from 'gatsby-link'
/* later down in the code... */
<nav>
<Link to='/about'>About The Blog</Link>
</nav>
Which would output:
<a href="/myBlog/about">About The Blog</a>
The issue is I don't want to hardcode myBlog anywhere in the source, not even in a config file. Conceptually I want the pathPrefix to be "." -- that is, relative to the app's path, so that the app could be deployed at any arbitrary path and still work. –
Megagamete
You could get away with relative links then? e.g. use
<a href="/about">About</a>
and it should work, no matter the path. –
Seraphim It's not just about links. It's also about loading resources like the JS files themselves. –
Megagamete
Can you programmatically set
pathPrefix
to the parent directory name within you gatsby-config.js file? I'm new to Gatsby, but for links to be resolved something needs to know your site's absolute path. –
Disconsider @JonathanMellman - this is as close as you can get I assume, but it's not enough, because this happens in build time, while the path might be determined later. A regular HTML page doesn't know what is its path, it just know that the rest of the static content is inside its folder. You can take this folder and drop it any where, and it will work, unless it's Gatsby. –
Distefano
You can use environment variables in the gatsby-config.js
file.
module.exports = {
pathPrefix: process.env.PREFIX
}
Then run PREFIX=/blog gatsby build
.
https://github.com/gatsbyjs/gatsby/issues/19481#issuecomment-554430699
© 2022 - 2024 — McMap. All rights reserved.