【问题标题】:Install Gatsby in the /blog directory在 /blog 目录中安装 Gatsby
【发布时间】:2019-10-06 22:58:07
【问题描述】:

我使用 Netlify 一键式按钮创建了一个 Gatsby 博客,但希望使用 index.html 拥有自己的主页登录页面,然后将 Gatsby 博客构建在我网站的 /blog 目录中(example.com/blog )

我查看了 config.js 和 gatsby-config.js 文件以获取更改构建位置的设置,此外我还在 Netlify 中尝试了一些不同的构建命令,例如

构建命令:gatsby build

发布目录:public/articles

任何人都可以帮助在特定文件夹(目录)中构建它,同时将我自己的 index.html 留在根目录中吗?

【问题讨论】:

  • 这个问题你还需要帮助吗?

标签: github gatsby netlify


【解决方案1】:

查看this starter 并阅读Gatsby tutorial Part 7

gatsby-node.js

const replacePath = path => (path === `/` ? path : path.replace(/\/$/, ``))
const { createFilePath } = require(`gatsby-source-filesystem`)
const path = require("path")

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `MarkdownRemark`) {
    const slug = createFilePath({ node, getNode, basePath: `blog` })
    createNodeField({
      node,
      name: `slug`,
      value: replacePath(slug),
    })
  }
}


exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions

  const postTemplate = path.resolve(`src/templates/postTemplate.js`)

  return graphql(`
    {
      allMarkdownRemark(
        sort: { order: DESC, fields: [frontmatter___date] }
        limit: 1000
      ) {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `).then(result => {
    if (result.errors) {
      return Promise.reject(result.errors)
    }

    result.data.allMarkdownRemark.edges.forEach(({ node }) => {
      createPage({
        path: replacePath(node.fields.slug),
        component: postTemplate
      })
    })
  })
}

onCreateNode 中,如果节点的内部类型为MarkdownRemark,则会创建一个基本路径为blog 的文件路径,并将新的文件路径添加到一个名为slug 的新节点字段中。

这个新字段现在可用于任何 graphQL 查询。

所以稍后在createPages 中,新的slug 字段被查询并用于createPage 路径选项。

因此,src/blog 文件夹中的页面将继续从根目录提供,而MarkdownRemark 生成的帖子将从/blog/ 提供

【讨论】:

    【解决方案2】:

    在 gatsby-config.js 中添加这个

    module.exports = {
      pathPrefix: `/blog`,
    
    

    在您构建应用程序时:

    gatsby build --prefix-paths
    

    【讨论】:

      【解决方案3】:

      您需要告诉 Gatsby 要将文件放在哪里。 Netlify 只想知道您的公用文件夹在哪里。

      gatsby build --output-dir public/articles
      

      然后您可以将自己的 index.html 文件移动到创建的目录 (public) 中,或者将其保存在其中*。

      我还建议让 Gatsby 运行您的整个站点,并为您的主页创建一个静态文件,这样您的构建过程就会简单得多,并且您可以在本地运行它。

      * 不确定这是否允许,Gatsby 可能需要一个空的或不存在的文件夹来构建。

      【讨论】:

      • 配置中有一个选项可以为我记得的博客文章添加前缀,因此它们显示为 /blog 但盖茨比网站的其余部分位于 / ,所有内容与博客相关。只想拥有自己的 index.html 主页,而不是使用 Markdown 作为我自己的自定义主页
      猜你喜欢
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 2018-02-22
      • 2017-12-29
      • 1970-01-01
      相关资源
      最近更新 更多