GatsbyJS - How to Add Slug Field
Add slug
field in gatsby-node.js
:
const { createFilePath } = require(`gatsby-source-filesystem`);
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions;
if (node.internal.type === `MarkdownRemark`) {
// ...
const slug = createFilePath({ node, getNode, basePath: `pages` });
createNodeField({
node,
name: `slug`,
value: slug,
});
// ...
}
};
slug
will be the file path after the pages
, e.g. if you have a page project_folder/src/pages/en/my_first_page.md
, the slug
would be /en/my_first_page/
.
Then the slug
can be queried by
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}