or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

config-loading.mdcore-preset.mddependencies.mdhook-optimization.mdindex.mdreact-preset-and-utilities.md
tile.json

config-loading.mddocs/

Configuration Loading

Utility functions for loading cached Babel configuration from Gatsby's build system. These functions provide access to optimized browser targets and other build-specific settings that are generated during the Gatsby build process.

Capabilities

Load Cached Configuration

Loads cached Babel configuration from Gatsby's .cache/babelState.json file.

/**
 * Loads cached Babel configuration from Gatsby's .cache/babelState.json
 * @returns {object} Cached plugin babel configuration object
 * @throws {Error} If not in test environment and cache file is missing
 */
function loadCachedConfig();

Usage Examples:

import { loadCachedConfig } from "babel-preset-gatsby";

// Load cached configuration (normally used internally by the preset)
try {
  const cachedConfig = loadCachedConfig();
  console.log("Browser targets:", cachedConfig.browserslist);
} catch (error) {
  // Handle missing cache file
  console.error("Cache file not found:", error.message);
}

// Safe usage with fallback
function getTargets() {
  try {
    const config = loadCachedConfig();
    return config.browserslist;
  } catch (error) {
    // Fallback for development or testing
    return { browsers: ["last 2 versions"] };
  }
}

Configuration Structure

The cached configuration object contains build-specific settings generated by Gatsby:

// Example cached configuration structure
{
  browserslist: {
    // Browser targeting configuration for @babel/preset-env
    browsers: ["last 2 versions", "not ie <= 11"]
  }
  // Additional build-specific settings may be included
}

Environment Behavior

The function behaves differently based on the environment:

Test Environment

When BABEL_ENV or NODE_ENV is set to "test", the function returns an empty configuration object:

// In test environment (NODE_ENV=test)
const config = loadCachedConfig();
// Returns: {}

Development/Production Environment

In non-test environments, the function attempts to load the cache file from ./.cache/babelState.json:

// In development or production
const config = loadCachedConfig();
// Returns: { browserslist: {...}, ... }

Error Handling

The function throws specific errors to help diagnose configuration issues:

Missing Cache File

If the cache file cannot be found, the function throws a descriptive error:

try {
  loadCachedConfig();
} catch (error) {
  // Error message:
  // "`babel-preset-gatsby` has been loaded, which consumes config generated by the Gatsby CLI. 
  // Set `NODE_ENV=test` to bypass, or run `gatsby build` first."
}

Other File System Errors

For other file system errors (permissions, corruption, etc.), the original error is re-thrown:

try {
  loadCachedConfig();
} catch (error) {
  // Original file system error is propagated
  console.error("File system error:", error);
}

Integration Patterns

Internal Usage

The function is primarily used internally by the main preset function:

// Internal usage pattern (from preset implementation)
function preset(_, options = {}) {
  const pluginBabelConfig = loadCachedConfig();
  const targets = pluginBabelConfig.browserslist;
  
  // Use targets in @babel/preset-env configuration
  return {
    presets: [
      ["@babel/preset-env", { targets }]
    ]
  };
}

External Usage

While primarily internal, the function can be used externally for advanced configuration:

import { loadCachedConfig } from "babel-preset-gatsby";

// Custom preset that uses Gatsby's cached config
function myCustomPreset() {
  const gatsbyConfig = loadCachedConfig();
  
  return {
    presets: [
      ["@babel/preset-env", {
        targets: gatsbyConfig.browserslist,
        // Custom configuration
      }]
    ]
  };
}

Development Workflow

Initial Setup

  1. Run gatsby develop or gatsby build to generate the cache file
  2. The cache file is created at ./.cache/babelState.json
  3. Subsequent Babel transformations can access the cached configuration

Cache Regeneration

The cache file is regenerated when:

  • Gatsby configuration changes
  • Browser target configuration changes
  • Dependencies are updated

Testing Considerations

For testing, either:

  • Set NODE_ENV=test to bypass cache loading
  • Ensure the cache file exists in your test environment
  • Mock the loadCachedConfig function in your tests
// Test environment bypass
process.env.NODE_ENV = "test";
const config = loadCachedConfig(); // Returns {}

// Or ensure cache exists for integration tests
beforeEach(() => {
  // Create mock cache file for tests
  fs.writeFileSync("./.cache/babelState.json", JSON.stringify({
    browserslist: { browsers: ["last 2 versions"] }
  }));
});