vite-plugin-glsl

repository·main·Indexed 19 days ago

https://github.com/ustymukhman/vite-plugin-glsl

A Vite plugin to import, inline, and minify GLSL, WGSL, and Slang shader files into JavaScript/TypeScript code. It features a custom #include system for modular shader development, support for multiple file extensions (.glsl, .vert, .frag, .slang, .wgsl, .vs, .fs), and a configurable onComplete hook for custom transformations. Version 1.6.1.

Tokens
3.5K
Snippets
15
Records
16
Agent score
61%

What's inside vite-plugin-glsl

  1. How shader chunk imports work

    main

    The plugin allows you to modularize shaders using a custom #include keyword. When you use #include path/to/file;, the plugin resolves the file, injects its content into the main shader, and handles dependencies recursively.

    Key behaviors:

    • Automatic Extensions: If you omit the extension in the #include statement (e.g., #include utils/chunk1), the plugin uses the defaultExtension option (defaulting to glsl) to find the file.
    • Deduplication: If removeDuplicatedImports is set to true, the plugin will automatically remove chunks that have already been included to prevent errors.
    • Three.js Compatibility: If using three.js r0.99+, standard Three.js includes like #include <common> are ignored by this plugin as they are handled by the library itself.
    // main.frag
    #include chunk0.frag;
    
    void main (void) {
      // ...
    }
    
    // chunk0.frag
    #include utils/chunk1; // Automatically resolves to utils/chunk1.glsl
    
    vec4 chunkFn () {
      return vec4(chunkRGB(), 1.0);
    }
  2. Enable TypeScript support for GLSL imports

    main

    To prevent TypeScript errors when importing shader files, you must declare the extensions. You can do this in two ways:

    1. Via tsconfig.json: Add vite-plugin-glsl/ext to your types array.
    2. Via Triple-Slash Directive: Add the reference to your global types file.
    // tsconfig.json
    {
      "compilerOptions": {
        "types": [
          "vite-plugin-glsl/ext"
        ]
      }
    }

    OR

    /// <reference types="vite-plugin-glsl/ext" />
  3. Use Slang Shaders with vite-plugin-glsl

    main
    Slang shaders are not supported out of the box. To use them (starting from v1.6.0), you must manually configure your vite.config to use multiple importKeywords for Slang chunks and use the onComplete option combined with a Slang compiler to convert the output to a web-friendly format like WGSL.
  4. Configure vite-plugin-glsl options

    main

    When calling the glsl() function, you can pass a configuration object to customize how shader files are discovered and processed.

    Available Options:

    OptionTypeDefaultDescription
    includestring[]['**/*.glsl', '**/*.wgsl', '**/*.vert', '**/*.frag', '**/*.vs', '**/*.fs']Glob patterns to include files for processing.
    excludestring[]undefinedGlob patterns to exclude files.
    defaultExtensionstring'glsl'The default extension used for shader files.
    warnDuplicatedImportsbooleantrueIf true, emits a warning when duplicate #include statements are detected.
    removeDuplicatedImportsbooleanfalseIf true, attempts to remove duplicate imports during processing.
    importKeywordsstring[]['#include']Keywords used to identify import statements within shader files.
    onCompletefunctionundefinedA callback function triggered after a shader is processed.
    minifybooleanfalseWhether to minify the resulting shader code.
    watchbooleantrueWhether to add dependent chunks to the Vite watcher (enabled by default in development).
    rootstring'/'The root directory for resolving shader imports.
    import glsl from 'vite-plugin-glsl';
    
    export default {
      plugins: [
        glsl({
          include: ['**/*.custom-shader'],
          exclude: ['**/node_modules/**'],
          minify: true,
          importKeywords: ['#include', '#import'],
          removeDuplicatedImports: true
        })
      ]
    };
  5. Configure vite-plugin-glsl via PluginOptions

    main

    The PluginOptions object is used to configure the plugin within your Vite configuration. It extends LoadingOptions and allows you to control which files are processed, how imports are handled, and whether to minify the output.

    Default Configuration

    If no options are provided, the plugin uses these defaults:

    • include: ['**/*.glsl', '**/*.wgsl', '**/*.vert', '**/*.frag', '**/*.vs', '**/*.fs']
    • exclude: undefined
    • defaultExtension: 'glsl'
    • warnDuplicatedImports: true
    • removeDuplicatedImports: false
    • importKeywords: ['#include']
    • onComplete: undefined
    • minify: false
    • watch: true
    • root: '/'
    // Example configuration structure
    import glsl from 'vite-plugin-glsl';
    
    export default {
      plugins: [
        glsl({
          include: '**/*.vert',
          exclude: '**/ignored/*.glsl',
          watch: true,
          minify: true,
          root: './src/shaders',
          importKeywords: ['#include', '#import'],
          onComplete: (shader, path) => {
            // Transform shader code here
            return shader;
          }
        })
      ]
    };
  6. Reference: glsl() configuration options

    main

    The glsl() plugin accepts an options object to control how shader files are processed, included, and transformed.

    glsl({
      include: [                      // Glob pattern, or array of glob patterns to import
        '**/*.glsl', '**/*.wgsl', 
        '**/*.vert', '**/*.frag', 
        '**/*.vs', '**/*.fs'
      ],
      exclude: undefined,             // Glob pattern, or array of glob patterns to ignore
      defaultExtension: 'glsl',       // Shader suffix to use when no extension is specified
      warnDuplicatedImports: true,    // Warn if the same chunk was imported multiple times
      removeDuplicatedImports: false, // Automatically remove an already imported chunk
      importKeywords: ['#include'],   // Keywords used to import shader chunks
      onComplete: undefined,          // Function to call with output shader
      minify: false,                  // Minify/optimize output shader code
      watch: true,                    // Recompile shader on change
      root: '/'                       // Directory for root imports
    })
  7. Initialize the glsl plugin

    main

    The glsl function is the main entry point for the Vite plugin. It returns a Vite plugin that allows you to import, inline, and optionally minify GLSL, WGSL, and Slang shader files. It accepts an optional PluginOptions configuration object.

    import glsl from 'vite-plugin-glsl';
    
    export default async function glsl(options?: PluginOptions): Promise<Plugin>;
  8. Initialize the vite-plugin-glsl plugin

    main

    The glsl function is the main entry point for the plugin. It returns a Vite plugin that allows you to import, inline, and optionally minify GLSL, WGSL, or Slang shader files directly into your JavaScript/TypeScript code. The plugin runs in the pre enforcement phase to ensure shaders are processed before other transformations.

    import glsl from 'vite-plugin-glsl';
    
    export default {
      plugins: [
        glsl({
          minify: true,
          // other options
        })
      ]
    };
  9. Import shader files in TypeScript

    main

    The vite-plugin-glsl plugin provides TypeScript ambient module declarations that allow you to import shader files directly into your TypeScript code as strings. This prevents TypeScript errors when using import statements for non-standard file extensions. Supported extensions include .glsl, .vert, .frag, .slang, .wgsl, .vs, and .fs.

    import vertexShader from './shaders/triangle.vert';
    import fragmentShader from './shaders/triangle.frag';
    
    // vertexShader and fragmentShader are treated as strings
    console.log(vertexShader);