or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-storybook--builder-vite

A Storybook builder to dev and build with Vite

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@storybook/builder-vite@9.1.x

To install, run

npx @tessl/cli install tessl/npm-storybook--builder-vite@9.1.0

index.mddocs/

Storybook Builder Vite

Storybook Builder Vite is a modern Storybook builder that integrates with Vite for fast development server startup times and near-instant hot module replacement (HMR) during component development. It serves as a drop-in replacement for webpack-based builders, providing significantly improved performance while maintaining full compatibility with Storybook's ecosystem.

Package Information

  • Package Name: @storybook/builder-vite
  • Package Type: npm
  • Language: TypeScript
  • Installation: Typically installed automatically when using Storybook with Vite framework packages

Core Imports

import { 
  start, 
  build, 
  bail, 
  withoutVitePlugins, 
  hasVitePlugins 
} from "@storybook/builder-vite";

For type imports:

import type { 
  ViteBuilder, 
  ViteFinal, 
  StorybookConfigVite, 
  BuilderOptions 
} from "@storybook/builder-vite";

Basic Usage

This package is typically not used directly by end users but is configured through Storybook's main configuration:

// .storybook/main.js
export default {
  framework: {
    name: '@storybook/react-vite', // or another Vite-based framework
    options: {
      builder: {
        viteConfigPath: '.storybook/customViteConfig.js', // optional
      },
    },
  },
  async viteFinal(config, { configType }) {
    // Customize Vite config for Storybook
    return mergeConfig(config, {
      resolve: {
        alias: { foo: 'bar' },
      },
    });
  },
};

Architecture

The Storybook Builder Vite integrates Vite's build system into Storybook's framework architecture:

  • Builder Interface: Implements Storybook's standardized Builder interface with start, build, and bail methods
  • Development Server: Uses Vite's dev server with HMR for fast component development and story updates
  • Production Build: Leverages Vite's optimized build process with Rollup for efficient static asset generation
  • Plugin System: Provides utilities for managing Vite plugins within Storybook's configuration system
  • Virtual File System: Handles Storybook's virtual modules and iframe HTML transformation through Vite's plugin API
  • Configuration Management: Supports custom Vite configurations through viteFinal hooks and external config files

The builder serves as the bridge between Storybook's component development workflow and Vite's modern build tooling, enabling fast startup times and near-instant hot reloading for an improved developer experience.

Capabilities

Builder Core Functions

Primary functions that implement the Storybook builder interface for development and production builds.

/**
 * Starts the Vite development server for Storybook
 * @param args - Configuration object with options, startTime, router, server, and channel
 * @returns Promise resolving to development server info with bail function and stats
 */
const start: (args: {
  options: Options;
  startTime: ReturnType<typeof process.hrtime>;
  router: ServerApp;
  server: HttpServer;
  channel: ServerChannel;
}) => Promise<void | {
  stats?: ViteStats;
  totalTime: ReturnType<typeof process.hrtime>;
  bail: (e?: Error) => Promise<void>;
}>;

/**
 * Builds Storybook for production using Vite
 * @param arg - Configuration object with options and startTime
 * @returns Promise resolving to build statistics
 */
const build: (arg: {
  options: Options;
  startTime: ReturnType<typeof process.hrtime>;
}) => Promise<void | ViteStats>;

/**
 * Gracefully shuts down the Vite development server
 * @param e - Optional error parameter
 * @returns Promise that resolves when server is closed
 */
function bail(e?: Error): Promise<void>;

Plugin Management Utilities

Utilities for managing Vite plugins in Storybook configurations, allowing developers to programmatically filter and check for specific plugins.

/**
 * Recursively removes all plugins with the specified names from a Vite plugins array
 * Resolves async plugins and handles nested plugin arrays
 * @param plugins - Array of Vite plugins (may include promises and nested arrays), defaults to empty array
 * @param namesToRemove - Array of plugin names to remove
 * @returns Promise resolving to filtered plugins array
 */
function withoutVitePlugins<TPlugin>(
  plugins?: TPlugin[],
  namesToRemove: string[]
): Promise<TPlugin[]>;

/**
 * Checks if any plugins in the array have names matching the provided names
 * Will resolve any promises in the plugins array and check nested arrays recursively
 * @param plugins - Array of Vite plugin options
 * @param names - Array of plugin names to check for
 * @returns Promise resolving to true if any matching plugins are found
 */
function hasVitePlugins(
  plugins: PluginOption[], 
  names: string[]
): Promise<boolean>;

Usage Examples:

import { withoutVitePlugins, hasVitePlugins } from '@storybook/builder-vite';
import type { PluginOption } from 'vite';

// Remove specific plugins from a Vite config
const cleanedPlugins = await withoutVitePlugins(
  viteConfig.plugins, 
  ['rollup-plugin-turbosnap']
);

// Check if certain plugins are present
const hasTurbosnap = await hasVitePlugins(
  viteConfig.plugins, 
  ['rollup-plugin-turbosnap']
);

Configuration Management

Types and interfaces for customizing Vite configuration within Storybook.

/**
 * Function type for customizing Vite configuration in Storybook
 * Called during Storybook's configuration phase to allow Vite config modifications
 * @param config - Current Vite InlineConfig object
 * @param options - Storybook options object
 * @returns Modified Vite configuration (sync or async)
 */
type ViteFinal = (
  config: InlineConfig,
  options: Options
) => InlineConfig | Promise<InlineConfig>;

/**
 * Storybook configuration interface with Vite-specific options
 * Used in .storybook/main.js configuration files
 */
interface StorybookConfigVite {
  /** Optional function to customize Vite configuration */
  viteFinal?: ViteFinal;
}

/**
 * Configuration options for the Vite builder
 * Used in framework.options.builder configuration
 */
interface BuilderOptions {
  /** Path to vite.config file, relative to process.cwd() */
  viteConfigPath?: string;
}

Types

Core type definitions for the builder interface and configuration.

/**
 * Main builder interface extending Storybook's Builder type with Vite-specific configuration
 * Generic parameters: Vite's UserConfig for configuration, ViteStats for build statistics
 */
type ViteBuilder = Builder<UserConfig, ViteStats>;

/**
 * Vite-specific stats object that replaces Webpack stats in Storybook
 * Provides JSON serialization method for build information
 */
interface ViteStats {
  /** Serializes build statistics to JSON format */
  toJson(): any;
}

/**
 * Storybook options interface from internal types
 * Contains configuration options passed to builders
 */
interface Options {
  // Storybook internal options type
  [key: string]: any;
}

/**
 * Server application interface for routing
 * Express-like server interface for middleware registration
 */
interface ServerApp {
  // Express-like server application
  [key: string]: any;
}

/**
 * HTTP server interface from Node.js
 * Standard Node.js HTTP server interface
 */
interface HttpServer {
  // Node.js HTTP server
  [key: string]: any;
}

/**
 * Server channel interface for Storybook communication
 * Used for communication between Storybook manager and preview
 */
interface ServerChannel {
  // Storybook server channel
  [key: string]: any;
}

/**
 * Vite user configuration interface from Vite
 * Standard Vite configuration object
 */
interface UserConfig {
  // Vite user configuration
  [key: string]: any;
}

/**
 * Vite inline configuration interface from Vite
 * Extended Vite configuration for programmatic usage
 */
interface InlineConfig {
  // Vite inline configuration
  [key: string]: any;
}

/**
 * Vite plugin option type from Vite
 * Represents various forms of Vite plugins (objects, functions, promises, arrays)
 */
type PluginOption = any;

Dependencies

Runtime Dependencies

  • @storybook/csf-plugin: Component Story Format plugin support
  • ts-dedent: Template string dedenting utility

Peer Dependencies

  • storybook: Main Storybook framework (required)
  • vite: Vite bundler (^5.0.0 || ^6.0.0 || ^7.0.0)

Common Usage Patterns

Custom Vite Configuration

// .storybook/main.ts
import type { StorybookConfig } from '@storybook/react-vite';
import { mergeConfig } from 'vite';

const config: StorybookConfig = {
  // ... other config
  async viteFinal(config, { configType }) {
    return mergeConfig(config, {
      define: {
        'process.env.NODE_ENV': JSON.stringify(
          configType === 'DEVELOPMENT' ? 'development' : 'production'
        ),
      },
      resolve: {
        alias: {
          '@': path.resolve(__dirname, '../src'),
        },
      },
    });
  },
};

export default config;

Plugin Management

// Remove problematic plugins in viteFinal
import { withoutVitePlugins } from '@storybook/builder-vite';

export default {
  async viteFinal(config) {
    // Remove specific plugins that conflict with Storybook
    config.plugins = await withoutVitePlugins(config.plugins || [], [
      'rollup-plugin-turbosnap'
    ]);
    return config;
  },
};

Builder Options Configuration

// .storybook/main.js - Custom Vite config path
export default {
  framework: {
    name: '@storybook/react-vite',
    options: {
      builder: {
        viteConfigPath: '.storybook/custom-vite.config.js',
      },
    },
  },
};