Importing GLSL Shaders in NextJS – How do I check if the Webpack loaders work?

Viewed 955

I am trying to load GLSL Shaders in my NextJS Application. I have configured my next.config.js like this:

module.exports = {
    reactStrictMode: true,
    images: {
        domains: [
            'localhost',
            'backend.rolideluxe.ch'
        ]
    },

    webpack: ( config, {} ) => {
        config.module.rules.push({
            test: /\.mp4$/,
            use: {
                loader: 'file-loader'
            }
        })

        config.module.rules.push({
            test: /\.(glsl|vs|fs|vert|frag)$/,
            use: {
                loader: 'raw-loader'
            }
        })

        return config
    },
}

This returns the error (the bottom part being the shader start of the shader)

./public/shaders/blob/vertex.glsl
Module parse failed: Unexpected token (2:8)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
> uniform vec2 uFrequency;

I am relatively new to NextJS and ThreeJS and have little more experience with Webpack. I have tried different loaders (like the glsl-shader-loader and the shader-loader), all with the same result. From what I've gathered, the error should lie in the intersection of Webpack and NextJS. Hence my two questions:

  1. How do I check if a Webpack loader works.
  2. Any Ideas how I could get my imports to work?
3 Answers

You can make it if you install glslify-loader and push it to rules

/** @type {import('next').NextConfig} */
module.exports = {
    reactStrictMode: true,
    webpack: (config, options) => {
        config.module.rules.push({
            test: /\.(glsl|vs|fs|vert|frag)$/,
            use: ['raw-loader', 'glslify-loader'],
        });

        return config;
    }
};

You do not need a loader. Here's the configuration you should use:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  webpack: (config) => {
    config.module.rules.push({
      test: /\.(frag|vert)$/,
      type: 'asset/source'
    })
    return config
  }
}

module.exports = nextConfig

Note the .frag, .vert file extension.

I was not able to get any glslify-loader to work with next.config.js, but it works great using inline import/require statements, like so:

// Using ES6 import statement
import source from 'raw-loader!glslify-loader!./public/shaders/blob/vertex.glsl'

// Using require
const source = require('raw-loader!glslify-loader!./public/shaders/blob/vertex.glsl')

as seen here at glslify-loader README.md https://github.com/glslify/glslify-loader

Related