'How to load WebGL Vertex and Fragment Shaders in ReactJs?
Let me put my question upfront, and then share related details: Is there a way we can use/load (fix parsing errors) WebGL shaders in ReactJS? Are there any loaders available?
After struggling for hours Googling for a way to be able to use shader files (i.e., Vertex and Fragment Shaders), I have found no conclusive solution yet.
When I do this in ReactJS app:
require('../shaders/particle.vert')import particleVert from '../shaders/particle.vert'
I get this error:
ERROR in ./src/particles/src/shaders/particle.vert 3:10
Module parse failed: Unexpected token (3:10)
You may need an appropriate loader to handle this file type.
This is how I'm using those shaders in my react-app code:
const material = new THREE.RawShaderMaterial({
uniforms,
vertexShader: glslify(require('../shaders/particle.vert')),
fragmentShader: glslify(require('../shaders/particle.frag')),
// vertexShader: glslify(particleVert),
// fragmentShader: glslify(particleFrag),
depthTest: false,
transparent: true,
// blending: THREE.AdditiveBlending
});
Here is a screenshot displaying entire log of the issue:
Solution 1:[1]
I think you are going outside the lines that create-react-app sets up for you. That means it's time to eject your app, and customize its build process.
Run:
npm run eject
Now you need to configure webpack to allow importing of frag and vert files as a string. This is done with webpack's 'raw-loader'
npm install raw-loader --save-dev
Now add some lines of configuration to the webpack.config.js file you should have in your directory root. You looking for where it defines module: { rules: { /*...*/ } }. Add the following rule to the array:
// Require .vert and .frag as raw text.
{
test: /\.(vert|frag)$/i,
use: 'raw-loader',
}
The test is a regex to run on the filename, so this says any file ending in .vert or .frag should use the raw-loader
Solution 2:[2]
UPDATE: with new react versions (with webpack > 5), we have to use asset/source. No npm/yarn install needed
{
test: /\.(glsl|vert|frag)$/,
type: 'asset/source',
},
Solution 3:[3]
react-three-fiber/drei is your best bet for a lightweight wrapper for three.js' rawshadermaterial. Here is the documentation:
https://docs.pmnd.rs/drei/shaders/shader-material
The docs are pretty straight forward and you can still import external files with glsify
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Wayne |
| Solution 2 | sugaith |
| Solution 3 | investInSoup |

