or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-usage.mdconfiguration.mdfile-system-routes.mdindex.md
tile.json

advanced-usage.mddocs/

Advanced Usage

Advanced configuration patterns, multiple plugin instances, and integration with Gatsby's programmatic page creation APIs.

Capabilities

Multiple Plugin Instances

Use multiple instances of the plugin to create pages from different directories.

/**
 * Multiple plugin instances configuration
 * Each instance can have different options and watch different directories
 */
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-page-creator`,
      options: {
        path: string;
        ignore?: IgnoreConfig;
        slugify?: ISlugifyOptions;
      }
    },
    // ... additional instances
  ],
}

Usage Examples:

// Different page directories
module.exports = {
  plugins: [
    // Public pages
    {
      resolve: `gatsby-plugin-page-creator`,
      options: {
        path: `${__dirname}/src/pages`,
      },
    },
    // Admin pages  
    {
      resolve: `gatsby-plugin-page-creator`,
      options: {
        path: `${__dirname}/src/admin/pages`, 
        ignore: [`*.test.js`],
      },
    },
    // Account pages
    {
      resolve: `gatsby-plugin-page-creator`,
      options: {
        path: `${__dirname}/src/account/pages`,
      },
    },
  ],
}

Override Default Behavior

Override the default src/pages behavior with custom configuration.

/**
 * Override default src/pages behavior
 * This replaces Gatsby's built-in page creator for src/pages
 */
{
  resolve: `gatsby-plugin-page-creator`,
  options: {
    path: `${__dirname}/src/pages`,
    ignore: Array<string>;
    slugify: ISlugifyOptions;
  },
}

Usage Example:

// Custom ignore patterns for default pages directory
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-page-creator`,
      options: {
        path: `${__dirname}/src/pages`,
        ignore: [
          `private-*.js`,
          `admin/**`,
          `*.test.{js,tsx}`,
        ],
        slugify: {
          separator: '_',
          lowercase: false,
        },
      },
    },
  ],
}

Integration with CreatePages API

Combine automatic page creation with programmatic page generation.

/**
 * Integration with Gatsby's createPages API
 * The plugin works alongside manual page creation
 */
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;
  // Manual page creation logic here
};

Usage Example:

// gatsby-node.js - Manual page creation alongside plugin
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;
  
  // Query for data
  const result = await graphql(`
    query {
      allMarkdownRemark {
        nodes {
          id
          frontmatter {
            slug
            template
          }
        }
      }
    }
  `);

  // Create pages with custom templates
  result.data.allMarkdownRemark.nodes.forEach((node) => {
    if (node.frontmatter.template === 'custom') {
      createPage({
        path: `/custom/${node.frontmatter.slug}`,
        component: require.resolve('./src/templates/custom-template.js'),
        context: {
          id: node.id,
        },
      });
    }
  });
};

File Watching and Hot Reloading

The plugin automatically watches for file changes during development.

/**
 * File watching capabilities
 * - Automatically creates pages when new component files are added
 * - Updates pages when existing component files are modified  
 * - Removes pages when component files are deleted
 * - Supports hot reloading during development
 */
interface FileWatchingFeatures {
  addedFiles: (filePath: string) => void;
  removedFiles: (filePath: string) => void;
  hotReloading: boolean;
}

Node Change Tracking

Advanced tracking of GraphQL node changes for collection routes.

/**
 * Node change tracking for collection routes
 * Automatically updates pages when source nodes change
 */
interface NodeChangeTracking {
  /** Track nodes that have been created since last page generation */
  changedNodesSinceLastPageCreation: {
    created: Map<string, NodeChangeInfo>;
    deleted: Map<string, NodeChangeInfo>;
  };
  /** Track which node types are used by collection routes */
  trackedTypes: Map<string, Set<string>>;
  /** Update pages when tracked nodes change */
  syncPages(): void;
}

interface NodeChangeInfo {
  id: string;
  contentDigest: string;
  type?: string;
}

Custom Path Generation

Advanced path generation for complex routing scenarios.

/**
 * Extract GraphQL model name from collection path
 * @param absolutePath - File path containing {Model.field} syntax
 * @returns GraphQL model name (e.g., "MarkdownRemark")
 * @example extractModel("/blog/{MarkdownRemark.slug}.js") => "MarkdownRemark"
 */
function extractModel(absolutePath: string): string;

/**
 * Extract all collection segments from a file path
 * @param absolutePath - File path with collection markers
 * @returns Array of collection segments including braces
 * @example extractAllCollectionSegments("/blog/{Model.field}/{Model.other}.js") => ["{Model.field}", "{Model.other}"]
 */
function extractAllCollectionSegments(absolutePath: string): Array<string>;

/**
 * Extract field names from collection path parts
 * @param filePart - Collection path segment with {Model.field} syntax
 * @returns Array of extracted field names
 * @example extractField("{Model.field__(Union)__bar}") => ["field__(Union)__bar"]
 */
function extractField(filePart: string): Array<string>;

/**
 * Extract field names without union type syntax
 * @param filePart - Collection path segment
 * @returns Array of field names with union syntax stripped
 * @example extractFieldWithoutUnion("{Model.field__(Union)__bar}") => ["field__bar"]
 */
function extractFieldWithoutUnion(filePart: string): Array<string>;

/**
 * Convert field access syntax for object traversal
 * @param filePart - Field path with __ separators
 * @returns Field path with . separators for use with _.get()
 * @example switchToPeriodDelimiters("frontmatter__slug") => "frontmatter.slug"
 */
function switchToPeriodDelimiters(filePart: string): string;

/**
 * Remove file extensions from paths
 * @param absolutePath - File path with extension
 * @returns Path without file extension
 * @example removeFileExtension("/blog/post.js") => "/blog/post"
 */
function removeFileExtension(absolutePath: string): string;

/**
 * Convert union syntax for GraphQL queries
 * @param filePart - Field part with (Union) syntax
 * @returns GraphQL union syntax with "... on Union"
 * @example convertUnionSyntaxToGraphql("field__(Union)__bar") => "field__... on Union__bar"
 */
function convertUnionSyntaxToGraphql(filePart: string): string;

/**
 * Compose multiple path transformation functions
 * @param functions - Array of transformation functions to chain
 * @returns Composed function that applies all transformations in sequence
 */
function compose(
  ...functions: Array<(filePart: string) => string>
): (filePart: string) => string;

/**
 * Generate route parameters from collection path and URL
 * @param urlTemplate - Collection route template path
 * @param urlPath - Generated URL path
 * @returns Object mapping parameter names to values
 */
function getCollectionRouteParams(
  urlTemplate: string, 
  urlPath: string
): Record<string, string>;

Error Handling and Debugging

Comprehensive error handling and debugging capabilities.

/**
 * Error codes and debugging
 */
enum PluginErrors {
  Generic = "12101",
  CollectionGraphQL = "12102", 
  CollectionBuilder = "12103",
  GeneratePath = "12104",
  CollectionPath = "12105",
  GraphQLResolver = "12106",
  RequiredPath = "12107",
  NonExistingPath = "12108",
  FileSystemAdd = "12109",
  FileSystemRemove = "12110"
}

interface ErrorContext {
  sourceMessage: string;
  filePath?: string;
  nodeId?: string;
}

Usage Examples:

// Enable verbose logging for debugging
process.env.gatsby_log_level = 'verbose';

// Error handling in gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-page-creator`,
      options: {
        path: `${__dirname}/src/pages`,
        // pathCheck: false, // Disable path validation if needed
      },
    },
  ],
}

Performance Optimization

Optimize plugin performance for large sites.

/**
 * Performance optimization options
 */
interface PerformanceOptions {
  /** Disable path existence checking for faster builds */
  pathCheck: boolean;
  
  /** Optimize ignore patterns for better performance */
  ignore: {
    patterns: string[];
    options: { nocase?: boolean };
  };
}

Usage Example:

// Optimized configuration for large sites  
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-page-creator`,
      options: {
        path: `${__dirname}/src/pages`,
        pathCheck: false, // Skip path validation for speed
        ignore: {
          patterns: [
            `**/*.test.{js,ts,tsx}`,
            `**/*.spec.{js,ts,tsx}`,
            `**/__tests__/**`,
            `**/node_modules/**`,
          ],
          options: { nocase: false }, // Case-sensitive for speed
        },
      },
    },
  ],
}

Plugin State Management

Access plugin instance state for advanced integration scenarios.

/**
 * Plugin instance state management
 * Each plugin instance maintains separate state
 */
interface IStatePerInstance {
  /** Track changes to source nodes */
  changedNodesSinceLastPageCreation: {
    deleted: Map<string, NodeInfo>;
    created: Map<string, NodeInfo>;
  };
  
  /** Map node types to template file paths */
  trackedTypes: Map<string, Set<string>>;
  
  /** Track pages created from each node */
  nodeIdToPagePath: Map<string, Map<string, string>>;
  
  /** Set of known page paths to avoid duplicates */
  knownPagePaths: Set<string>;
  
  /** Synchronize pages based on node changes */
  syncPages?(): void;
  
  /** Clean up when template files are removed */
  templateFileRemoved(absolutePath: string): void;
}