How can I import glsl as string in TypeScript?
Asked Answered
P

3

19

I am working at a WebGL project by TypeScript. There are many shaders written by glsl, and I want to import them as string in my ts file. Like:

import fxaa from "./shaders/fxaa";
const fxaaShader = new Shader(fxaa); // pass as string

Can I do it ?

Provoke answered 12/2, 2018 at 7:41 Comment(1)
Can you give an example of what the shader file (./shaders/fxaa) looks like?Zoom
S
34

Late to the party here, but just add a declaration file glsl.d.ts:

declare module '*.glsl' {
  const value: string
  export default value
}

...then import as string:

import shaderVert from './shaders/vertex.glsl'

...and if you're using webpack you'll need ts-shader-loader

Scour answered 30/3, 2019 at 0:57 Comment(2)
This works great, but I'm curious why it only works when the module name starts with an asterisk (*). Is there any reason behind that behaviour?Ackerley
Probably pretty late with this answer but this import will work for any file that has the .glsl extension, the * sign serves as the "all" selector meaning that it doesn't matter how your file is named as long as it has the proper extension.Executive
T
0

When using vite, you could do something like:

import fxaa from './shaders/fxaa?raw'

(docs)

When using webpack, you can define a 'asset/source' module type in your webpack config file, and import like this:

import fxaa from './shaders/fxaa';

(docs)

Tedie answered 26/4, 2024 at 14:49 Comment(0)
Z
-2

It depends on how the shader file (./shader/fxaa, in your example) is written. If you are writing this shader file yourself, you could do something like this:

const fxaa = 'my shader code here';
export { fxaa };

And then use this shader code:

import { fxaa } from './shader/fxaa';
const fxaaShader = new fxaaShader(fxaa);

Alternatively, you could write the shader file (./shader/fxaa.json) like this:

"my shader code here"

And require this file as a JSON object:

const fxaa = require('./shader/fxaa.json');
const fxaaShader = new fxaaShader(fxaa);
Zoom answered 12/2, 2018 at 13:25 Comment(2)
It seems the best way to import glsl is to use loader of webpack/rollup...Provoke
You miss the whole point of the .glsl source being pure GLSL and editable (syntax highlight, error checking, and stuff) in an editor.Canto

© 2022 - 2025 — McMap. All rights reserved.