glsl-transpiler
raw JSON →Transforms GLSL shader source code into optimized JavaScript, converting vectors and matrices to arrays, expanding swizzles, and applying expression optimizations. The latest version (2.0.21) ships as an ESM package with optional CommonJS support. It works both as a programmatic API and as a stream transform, integrating with glsl-parser and glsl-tokenizer. Key differentiators include runtime variable replacement for uniforms/attributes/varyings, built-in stdlib for environment compatibility, debug facilities (print/show), and support for GLSL ES 100 and 300. Alternatives like glsl.js or raw string manipulation lack its AST-level optimization and streaming pipeline. The package is a fork of the original stackgl/glsl-transpiler with ongoing maintenance.
Common errors
error Cannot find module 'glsl-transpiler' or its corresponding type declarations. ↓
error TypeError: GLSL is not a constructor ↓
error Error: Invalid GLSL version. Must be '100' or '300 es'. ↓
error TypeError: Cannot read properties of undefined (reading 'type') ↓
Warnings
breaking Version 2.x drops Node.js 10 support and requires ESM imports or newer Node.js with --experimental-modules. ↓
deprecated The stream API import path changed from 'glsl-transpiler/stream' to 'glsl-transpiler/stream.js'. ↓
gotcha The default export is a factory function, not a class. Calling new GLSL() will cause a TypeError. ↓
gotcha texture2D expects an ndarray or an object with width/height properties, not a plain array. ↓
deprecated The 'includes' option now expects an object with function names to include, not just a boolean. ↓
breaking Removed support for GLSL version '100 es' in favor of '100' and '300 es'. ↓
Install
npm install glsl-transpiler-fork-for-gm yarn add glsl-transpiler-fork-for-gm pnpm add glsl-transpiler-fork-for-gm Imports
- default wrong
const GLSL = require('glsl-transpiler')correctimport GLSL from 'glsl-transpiler' - compileStream wrong
const compile = require('glsl-transpiler/stream')correctimport compile from 'glsl-transpiler/stream.js' - GLSL type
import type { CompilerOptions } from 'glsl-transpiler'
Quickstart
import GLSL from 'glsl-transpiler';
const compile = GLSL({
uniform: (name) => `uniforms.${name}`,
attribute: (name) => `attributes.${name}`,
version: '300 es',
optimize: true
});
const result = compile(`
precision mediump float;
attribute vec2 uv;
attribute vec4 color;
varying vec4 fColor;
uniform vec2 uScreenSize;
void main(void) {
fColor = color;
vec2 position = vec2(uv.x, -uv.y) * 1.0;
position.x *= uScreenSize.y / uScreenSize.x;
gl_Position = vec4(position, 0, 1);
}
`);
console.log('Compiled JS:', result);