or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-gatsby-transformer-yaml

Gatsby transformer plugin for parsing YAML files and converting them into GraphQL nodes

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/gatsby-transformer-yaml@5.15.x

To install, run

npx @tessl/cli install tessl/npm-gatsby-transformer-yaml@5.15.0

index.mddocs/

Gatsby Transformer YAML

Gatsby Transformer YAML is a Gatsby transformer plugin that parses YAML files (.yaml, .yml) and converts them into GraphQL nodes. It integrates with gatsby-source-filesystem to automatically process YAML files and make their content available through Gatsby's GraphQL data layer with support for both single objects and arrays of objects.

Package Information

  • Package Name: gatsby-transformer-yaml
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install gatsby-transformer-yaml
  • Peer Dependencies: gatsby ^5.0.0-next

Core Imports

This plugin is installed and configured in gatsby-config.js rather than imported directly into code:

module.exports = {
  plugins: [
    `gatsby-transformer-yaml`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `./src/data/`,
      },
    },
  ],
}

Basic Usage

// gatsby-config.js - Basic configuration
module.exports = {
  plugins: [
    `gatsby-transformer-yaml`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `./src/data/`,
      },
    },
  ],
}

// Example data file: src/data/products.yaml
- name: "Laptop"
  price: 999
  category: "electronics"
- name: "Book"
  price: 29
  category: "education"

// GraphQL Query in component
query {
  allProductsYaml {
    edges {
      node {
        name
        price
        category
      }
    }
  }
}

Architecture

The plugin operates within Gatsby's build-time data processing pipeline:

  • Node Processing: Implements Gatsby's Node API to identify and transform YAML files
  • YAML Parsing: Uses js-yaml library to parse YAML content into JavaScript objects
  • GraphQL Integration: Creates typed GraphQL nodes that can be queried using Gatsby's data layer
  • Type Generation: Automatically generates GraphQL type names based on file/directory structure
  • Parent-Child Relationships: Maintains relationships between source files and generated YAML nodes

Capabilities

Node Filtering

Determines which nodes should be processed by the transformer based on media type.

/**
 * Determines if a node should be processed by this transformer
 * @param {object} context - Context object containing the node
 * @param {object} context.node - The Gatsby node to check
 * @returns {boolean} - True if node should be processed (media type is 'text/yaml')
 */
function shouldOnCreateNode({ node }) {
  return node.internal.mediaType === `text/yaml`
}

YAML Node Creation

Processes YAML files and creates GraphQL nodes with automatic type naming and data structure handling.

/**
 * Main transformer function that processes YAML files and creates GraphQL nodes
 * @param {object} context - Gatsby node processing context
 * @param {object} context.node - The file node being processed
 * @param {object} context.actions - Gatsby actions (createNode, createParentChildLink)
 * @param {function} context.loadNodeContent - Function to load file content
 * @param {function} context.createNodeId - Function to generate unique node IDs
 * @param {function} context.createContentDigest - Function to create content digest
 * @param {object} pluginOptions - Plugin configuration options
 * @param {string|function} pluginOptions.typeName - Custom type name configuration
 * @returns {Promise<void>} - Resolves when processing is complete
 */
async function onCreateNode(
  { node, actions, loadNodeContent, createNodeId, createContentDigest },
  pluginOptions
)

Configuration Options

The plugin accepts a typeName option to customize GraphQL type naming:

interface PluginOptions {
  /**
   * Custom type name configuration
   * - String: Static type name for all YAML nodes
   * - Function: Dynamic type name based on content/context
   */
  typeName?: string | TypeNameFunction;
}

/**
 * Function to dynamically determine GraphQL type names
 * @param {object} context - Type naming context
 * @param {object} context.node - The source file node
 * @param {object} context.object - The YAML object being processed
 * @param {boolean} context.isArray - Whether the object is from an array
 * @returns {string} - GraphQL type name to use
 */
type TypeNameFunction = (context: {
  node: object;
  object: object;
  isArray: boolean;
}) => string;

Configuration Examples:

// Static type name
{
  resolve: `gatsby-transformer-yaml`,
  options: {
    typeName: `Yaml`, // All nodes will be type "Yaml"
  },
}

// Dynamic type name based on content
{
  resolve: `gatsby-transformer-yaml`,
  options: {
    typeName: ({ node, object, isArray }) => {
      if (object.type) {
        return object.type; // Use 'type' field from YAML content
      }
      return isArray ? `${node.name}Item` : `${node.name}Data`;
    },
  },
}

Data Processing Patterns

Array of Objects Pattern

When YAML files contain arrays, each array item becomes a separate GraphQL node:

# products.yaml
- name: "Laptop"
  price: 999
- name: "Book"
  price: 29

Results in GraphQL type: ProductsYaml (based on filename)

query {
  allProductsYaml {
    edges {
      node {
        name
        price
      }
    }
  }
}

Single Object Pattern

When YAML files contain single objects, the directory structure determines type naming:

data/
  products/
    laptop.yml    # Single object
    book.yml      # Single object
# laptop.yml
name: "Laptop"
price: 999

Results in GraphQL type: ProductsYaml (based on directory name)

ID Field Handling

The plugin automatically handles the reserved 'id' field:

# Input YAML
id: "product-123"
name: "Laptop"

# Resulting GraphQL node
{
  id: "generated-gatsby-id",      # Gatsby's internal ID
  yamlId: "product-123",          # Original 'id' field renamed
  name: "Laptop"
}

Type Definitions

/**
 * Generated YAML node structure
 */
interface YamlNode {
  /** Gatsby's unique node identifier */
  id: string;
  /** Array of child node IDs */
  children: string[];
  /** Parent node ID (the source file) */
  parent: string;
  /** Gatsby internal node metadata */
  internal: {
    /** Content-based hash for caching */
    contentDigest: string;
    /** GraphQL type name */
    type: string;
  };
  /** Original 'id' field if present in YAML */
  yamlId?: string;
  /** All other fields from the YAML content */
  [key: string]: any;
}

Dependencies

The plugin uses these key dependencies:

  • js-yaml: YAML parsing and conversion to JavaScript objects
  • lodash: Utility functions for type checking and string manipulation
  • @babel/runtime: Babel runtime helpers for transpiled code

Error Handling

The plugin relies on js-yaml for parsing, which will throw errors for invalid YAML syntax. Common issues include:

  • Invalid YAML syntax (indentation, formatting)
  • Unsupported YAML features (some advanced YAML constructs may not be supported)
  • File encoding issues (ensure UTF-8 encoding)

Troubleshooting

GraphQL Type Not Appearing

GraphQL types (allXxxYaml) will only appear if YAML files are present and successfully processed. Ensure:

  1. gatsby-source-filesystem is configured to read your YAML directory
  2. YAML files have .yaml or .yml extensions
  3. YAML files contain valid syntax
  4. Files are not empty or contain only comments

Reserved Field Names

If your YAML contains an id field, it will be automatically renamed to yamlId to avoid conflicts with Gatsby's internal id field.