从 next.js 加载着色器

Th0*_*gal 3 javascript shader webgl next.js

我正在为我的网络应用程序使用 next.js。我使用 WebGL 渲染 2d 场景。我的 javascript 中有一个片段和一个顶点着色器硬编码为字符串:

var fragmentShaderSource = [
    `  #ifdef GL_ES`,
    `precision highp float;`,
    `  #endif`,
    ``,
    `uniform vec4 uGlobalColor;`,
    ``,
    `void main() {`,
    `  gl_FragColor = uGlobalColor;`,
    `}`,
].join("\n");

...

let shader = gl.createShader(type);

gl.shaderSource(shader, fragmentShaderSource);
gl.compileShader(shader);
Run Code Online (Sandbox Code Playgroud)

这很糟糕,我更愿意使用单独的fragment.glsl和vertex.glsl文件进行开发(即使编译版本最后得到一个硬编码的字符串)。我读过有关 webpack 的内容,但这是我第一次使用 next/webpack,我不确定要做什么(示例已有 6 年或更长的历史)。

Th0*_*gal 5

这是使用原始加载程序的解决方案。这是我的 next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: (config, options) => {
    config.module.rules.push({
      test: /\.glsl/,
      type: "asset/source",
    })
    return config
  },
}

module.exports = nextConfig
Run Code Online (Sandbox Code Playgroud)

我现在可以这样导入我的着色器代码:

import fragmentShader from '../../shaders/fragment.glsl'
import vertexShader from '../../shaders/vertex.glsl'
Run Code Online (Sandbox Code Playgroud)