4

我不明白Gatsbybasepathpath prefixin之间的区别,以及何时使用每个功能

基本路径:https ://www.gatsbyjs.org/tutorial/part-seven/

路径前缀:https ://www.gatsbyjs.org/docs/path-prefix/

4

2 回答 2

1

理解 Gatsby 中的路径生成很棘手,因为有很多因素在起作用:

  • 你如何设置你的项目目录?
  • 你如何配置gatsby-source-filesystem
  • 如果您以编程方式创建页面gatsby-node.js,您将什么传递给API的path字段?createPages

由于 OP 说他们所有的站点 URL 都带有前缀blog/,这意味着他们已经设置为在相对于其域根目录path prefix的路径上为整个站点提供服务。与此无关。blog/basePath

除非您非常确定要/在域根目录以外的不同路径上为整个 Gatsby 站点提供服务,否则我建议您不要对path prefix.

继续 Derek Nguyen 的例子:

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/content`,
        name: 'content'
      }
    }
  ]
}

gatsby-node.js中,当你调用 的函数createFilePathgatsby-source-filesystem,你会得到两个 Markdown 文件的相对路径,如下所示:

  • /writing/page1
  • /images/cat

然后,如果您按照这个Gatsby 教程创建页面,这些文件应该生成为两个 HTML 页面:

  • localhost:8000/blog/writing/page1
  • localhost:8000/blog/images/cat

在这种情况下,您是否使用basePath并不重要。它只是一个从文件路径中删除公共路径的辅助函数。您无法删除/blog,因为它是由 设置的path prefix

但是,假设您决定cat.md/imagesdirectory 移动到/writing, basePath 可以派上用场。实际上,你应该,因为没有理由cat.md应该在/images目录下。

<root>
  |--content
  |     |--writing
  |     |    `--page1.md
             `--cat.md
  |
  |--gatsby-config.js
 ...

现在,为每个 Markdown 文件生成的路径将更改:

  • /writing/page1/
  • /writing/cat/

您可以writing通过如下方式将其从 url中删除basePath

const { createFilePath } = require('gatsby-source-filesystem')
exports.onCreateNode({ node, getNode }) => {
  if (node.internal.type === 'MarkdownRemark') {
    console.log(createFilePath({ node, getNode, basePath: 'writing' }))
  }
}

重新启动开发服务器,您应该会看到您的降价页面将在以下位置提供:

  • localhost:8000/blog/page1
  • localhost:8000/blog/cat
于 2020-09-17T04:51:54.630 回答
1

TL:博士

pathPrefix对您的网站有更大的影响——它为您所有页面和资产的生成 url 添加一个前缀。basePath只是从文件系统生成 slug 的助手——根据我使用 Gatsby 的经验,我很少使用它。


路径前缀

它将前缀附加到您所有页面和资产的 url。这样,您可以将 Gatsby 站点部署为另一个站点的子目录。

Without Prefix             | With 'blog' Prefix
---------------------------|--------------------------------
myblog.com/                | myblog.com/blog
myblog.com/hello/          | myblog.com/blog/hello
myblog.com/image-123.png   | myblog.com/blog/image-123.png

基本路径

这是一个选项,createFilePath可以帮助您从项目结构中创建 slug。它不会影响您是否从 root 服务您的 Gatsby。

如果你的项目目录是这样的:

<root>
  |--content
  |     |--writing
  |     |    `--page1.md
  |     `--images
  |          `--cat.md
  |
  |--gatsby-config.js
 ...

你在你的 gatsby-config.js 中设置它

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/content`,
        name: 'content'
      }
    }
  ]
}

然后createFilePath将为您的文件返回此 slug: writing/page1/,这可能不是您想要的。也许你希望它是/page1/。在这种情况下,设置basePathwriting将返回/page1/

于 2020-02-18T02:34:14.410 回答