Skip to content

Instantly share code, notes, and snippets.

@CodyJasonBennett
Last active August 13, 2022 17:35
Show Gist options
  • Save CodyJasonBennett/f0e641718554fdfaf8d70e945bf154ca to your computer and use it in GitHub Desktop.
Save CodyJasonBennett/f0e641718554fdfaf8d70e945bf154ca to your computer and use it in GitHub Desktop.
vite - glslx webgl2
import * as vite from 'vite'
import * as path from 'path'
import * as fs from 'fs'
// @ts-ignore
import glslx from 'glslx'
export default vite.defineConfig(({ command }) => ({
build: {
target: 'esnext',
polyfillModulePreload: false,
},
plugins: [
{
name: 'vite-glsl',
async transform(source, url) {
if (!url.endsWith('.glsl')) return
// Prioritize same dir, then check absolute imports & dependencies
const targets = [path.dirname(url)]
let code = source.replace(/^#include (.*?)$/gm, (_, file) => {
// Resolve against targets and return file source
for (const target of targets) {
const resolved = path.resolve(target, file)
if (fs.existsSync(resolved)) return fs.readFileSync(resolved, { encoding: 'utf-8' })
}
// No match found, return empty string to remove #include
return ''
})
if (command === 'build') {
// Compile and convert GLSL to 100
const compiled = glslx.compile(
code
.replace('#version 300 es', '#version 100')
.replaceAll('texture(', 'texture2D(')
.replaceAll(/[^\w]?(in|out) /gm, (_, type) => `varying ${type === 'in' ? 'highp' : 'mediump'} `),
{ renaming: 'none' }, // TODO: safely rename varyings
)
if (compiled.log) throw compiled.log
// Parse and convert GLSL back to 300 es
code = JSON.parse(compiled.output)
.shaders[0].contents.replace('#version 100', '#version 300 es')
.replaceAll('texture2D(', 'texture(')
.replaceAll('varying highp ', 'in ')
.replaceAll('varying mediump ', 'out ')
}
return vite.transformWithEsbuild(code, url, {
format: 'esm',
loader: 'text',
minifyWhitespace: true,
sourcemap: 'external',
})
},
},
],
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment