gatsby-source-filesystem在主题中使用时不从站点目录中获取文件



我试图建立一个盖茨比主题,使用gatsby-source-filesystem源图像。

我已经为开发设置了一个yarn工作区,我的文件夹结构看起来像这样。

workspace/
├─ example.com/
│  ├─ src/
│  │  ├─ pages/
│  │  │  ├─ test.js
│  ├─ gatsby-config.js
│  ├─ package.json
├─ gatsby-theme-example/
│  ├─ src/
│  ├─ images/
│  ├─ gatsby-config.js
│  ├─ gatsby-node.js
│  ├─ package.json

yarn工作空间也正确设置,并且gatsby-theme-example是它的依赖项。yarn workspaces info正确地显示了workspaceDependencies

两个工作区都有一个gatsby-config.js文件,gatsby-theme-example中有gatsby-source-filesystem文件。

{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: path.join(__dirname, "images"),
},
},

我面临的问题是,我必须把图像在主题目录图像文件夹内,否则它们不会被gatsby-source-filesystem找到。通过观看本视频和阅读教程,使用path.join__dirname变量应该指向将主题作为依赖项安装的包,在我的例子中是example.com

奇怪的是,gatsby-theme-example/gatsby-config.js中的gatsby-plugin-page-creator插件完美地创建了example.com/src/pages(网站目录)中定义的页面。

{
resolve: "gatsby-plugin-page-creator",
options: {
path: path.join(__dirname, "src/pages"),
},
},

我还在gatsby-theme-example/gatsby-node.js中定义了onPreBootstrap,像这样

exports.onPreBootstrap = ({ reporter }) => {
const contentPath = `${__dirname}/images/`
if (!fs.existsSync(contentPath)) {
reporter.info(`creating the ${contentPath} directory`)
fs.mkdirSync(contentPath)
}
}

gatsby-theme-example而不是example.com中创建images目录

我使用gatsby@4.18.0gatsby-source-filesystem@4.18.0,并使用以下命令启动项目:yarn workspace example.com start

我已经建立了一个repo,你可以用它来重现这个问题,像这样:

  1. git clone https://github.com/AlexanderProd/gatsby-source-filesystem-theme-bug
  2. yarn workspace example.com install
  3. yarn workspace example.com start
  4. 转到http://localhost:8000/___graphql
  5. 运行以下查询
query MyQuery {
allFile {
edges {
node {
id
name
}
}
}
}

不确定是否应该这样做,但我找到了一个解决方案。

在指定主题的站点gatsby-config.js(example.com/gatsby-config.js)中,我添加了一个图像路径选项。

{
resolve: `gatsby-theme-example`,
options: {
imagesPath: path.join(__dirname, "images"),
},
},

,然后在主题gatsby-config.js我使用的选项值。

module.exports = options => ({
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: options.imagesPath,
},
},
]
})

另一个解决方案,在这种情况下,最优的解决方案是仅使用images作为路径。

{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `images`,
},
},

基于这个答案。

最新更新