在 Gatsby 配置文件中使用对象

Using an Object in Gatsby Config File

我正在尝试更好地组织我的 gatsby 配置文件,但我不确定我做的是否正确。有谁知道以下设置是否有效:

module.exports = {
  plugins: [
    { gatsby_plugin__manifest },
    { gatsby_source__file_system__images },
    { gatsby_source__file_system__posts },
  ],
};

const gatsby_plugin__manifest = {
  resolve: `gatsby-plugin-manifest`,
  options: {
    name: `gatsby-starter-default`,
    short_name: `starter`,
    start_url: `/`,
    background_color: `#663399`,
    theme_color: `#663399`,
    display: `minimal-ui`,
    icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
  },
}

const gatsby_source__file_system__images = {
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `images`,
    path: `${__dirname}/src/images`,
  },
}

const gatsby_source__file_system__posts = {
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `posts`,
    path: `${__dirname}/src/posts/`,
  },
}

我收到一条错误消息 gatsby_plugin__manifest is not defined,我想知道这是否是因为我设置文件的方式?

使用 constlet 声明的变量不会被提升,因此无法在声明前引用它们。将 module.exports 放在声明下方,它应该可以工作。

我在这里看到两个问题:

根据 Gatbsy 文档,plugins 是一个字符串或对象数组。在 ES6 中,{ gatsby_plugin__manifest }, 是 shorthand for { gatsby_plugin__manifest: gatsby_plugin__manifest },一个 key-value 对。删除对象语法可以解决该问题。

其次,在导出中引用它之前声明 gatsby_plugin__manifest 会导致 ReferenceError,原因在 .

中描述

总结这些建议,仅针对其中一个插件:

// Declare gatsby_plugin__manifest before export
const gatsby_plugin__manifest = {
  resolve: `gatsby-plugin-manifest`,
  options: {
    // ...configuration here
  },
}

// Remove object syntax around gatsby_plugin__manifest
module.exports = {
  plugins: [
    gatsby_plugin__manifest,
  ],
};

Gatsby Config Docs