Reusable Snippets

Writing Reusable WGSL Snippets Across Shaders

WGSL has no #include or import; a module is one string. The simplest reuse is string composition, such as createShaderModule({ code: BOOK_WGSL + shading + main }) with the struct from demos/ch04/catalog.js. Then a message's lineNum counts lines of the combined string, so subtract the snippets in front. For larger code bases, WESL (WGSL Extended Shading Language) adds import statements and @if conditional compilation, and its linker, wesl-js 46 (github.com/webgpu-tools/wesl-js (https://github.com/webgpu-tools/wesl-js 46 ), MIT or Apache-2.0, npm 2,036 install wesl, 0.7.31), turns modules back into plain WGSL at build time or run time:

link.mjs: linking two WESL modules into one WGSL shader with Node.jsJavaScript
import { link } from 'wesl/core';
const weslSrc = {
  './prices.wesl': `
fn salePrice(price: f32, percentOff: f32) -> f32 {
  return round(price * (100 - percentOff)) / 100;
}
fn unused() -> f32 { return 0; }`,
  './main.wesl': `
import package::prices::salePrice;
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
@compute @workgroup_size(1) fn main() {
  @if(HOLIDAY) out[0] = salePrice(14.99, 25);
  @else out[0] = salePrice(14.99, 15);
}`,
};
const linked = await link({ weslSrc, rootModuleName: 'main', conditions: { HOLIDAY: false } });
console.log(linked.dest.trim());
Output
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
@compute @workgroup_size(1) fn main() {
  out[0] = salePrice(14.99, 15);
}
fn salePrice(price: f32, percentOff: f32) -> f32 {
  return round(price * (100 - percentOff)) / 100;
}

The linker dropped unused() and chose the @else branch; the result printed out: 12.739999771118164 in the lab.

WGSL snippets shared by string composition between a compute shader and a render shader, with line numbers corrected for the prefixHTMLLive
<!doctype html>
<style>
  body { margin: 0; background: #f7f4ee; font: 14px system-ui, sans-serif; }
  .stage { position: relative; width: 100%; max-width: 600px; }
  .stage canvas { display: block; width: 100%; }
  .stage canvas + canvas { position: absolute; inset: 0; pointer-events: none; }
</style>
<div class="stage">
  <canvas id="view" width="600" height="340"></canvas>
  <canvas id="labels" width="600" height="340"></canvas>
</div>
<script>
const canvas = document.getElementById('view');
const ink = document.getElementById('labels').getContext('2d');

function showMessage(text) {                     // 2D fallback when WebGPU is missing
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = '#fbeaea'; ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#8a2b2b'; ctx.font = '18px system-ui, sans-serif'; ctx.textAlign = 'center';
  ctx.fillText(text, canvas.width / 2, canvas.height / 2);
}
function label(text, x, y, size = 12, color = '#2b2b2b', font = 'system-ui, sans-serif', align = 'left') {
  ink.font = `${size}px ${font}`; ink.fillStyle = color; ink.textAlign = align; ink.fillText(text, x, y);
}

// Snippets: WGSL has no #include, so modules are assembled from strings.
const BOOK_WGSL = /* wgsl */ `
struct Book { price: f32, rating: f32, inStock: f32, tint: f32 }
@group(0) @binding(0) var<storage, read_write> books: array<Book>;`;
const PRICING = /* wgsl */ `
fn salePrice(price: f32, percentOff: f32) -> f32 {
  return round(price * (100 - percentOff)) / 100;
}`;
const SHADING = /* wgsl */ `
fn coverColor(tint: f32, uv: vec2f) -> vec3f {
  let base = mix(vec3f(0.08, 0.40, 0.75), vec3f(0.85, 0.40, 0.20), tint);
  return base * (0.7 + 0.3 * smoothstep(0.0, 0.15, uv.x));
}`;
const computeMain = /* wgsl */ `
@compute @workgroup_size(6) fn discount(@builtin(local_invocation_index) i: u32) {
  books[i].price = salePrice(books[i].price, 15);
}`;
const renderMain = /* wgsl */ `
struct Out { @builtin(position) pos: vec4f, @location(0) uv: vec2f, @location(1) @interpolate(flat) i: u32 }
@vertex fn vs(@builtin(vertex_index) v: u32, @builtin(instance_index) i: u32) -> Out {
  let q = vec2f(f32(v & 1), f32(v >> 1));
  let h = books[i].price / 40;                              // the discounted price sets the height
  return Out(vec4f(-0.9 + f32(i) * 0.3 + q.x * 0.24, -0.35 + q.y * h * 1.1, 0, 1), q, i);
}
@fragment fn fs(in: Out) -> @location(0) vec4f { return vec4f(coverColor(books[in.i].tint, in.uv), 1); }`;
const buggyMain = `
@compute @workgroup_size(1) fn broken() {
  books[0].price = salePrice(books[0].price);
}`;

async function main() {
  const adapter = await navigator.gpu?.requestAdapter();
  if (!adapter) return showMessage('WebGPU is not available in this browser');
  const device = await adapter.requestDevice();
  const context = canvas.getContext('webgpu');
  const format = navigator.gpu.getPreferredCanvasFormat();
  context.configure({ device, format });

  // A message's lineNum counts lines of the combined string, so subtract the prefix.
  const prefix = BOOK_WGSL + PRICING;
  device.pushErrorScope('validation');
  const info = await device.createShaderModule({ code: prefix + buggyMain }).getCompilationInfo();
  await device.popErrorScope();
  const err = info.messages.find((m) => m.type === 'error');
  const prefixLines = prefix.split('\n').length - 1;

  const computeModule = device.createShaderModule({ code: BOOK_WGSL + PRICING + computeMain });
  const renderModule = device.createShaderModule({ code: BOOK_WGSL.replace('read_write', 'read') + SHADING + renderMain });
  const compute = device.createComputePipeline({ layout: 'auto', compute: { module: computeModule } });
  const render = device.createRenderPipeline({ layout: 'auto', primitive: { topology: 'triangle-strip' },
    vertex: { module: renderModule }, fragment: { module: renderModule, targets: [{ format }] } });
  const prices = [14.99, 39.50, 24.00, 18.75, 16.20, 21.30];
  const books = device.createBuffer({ size: 96, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
  device.queue.writeBuffer(books, 0, new Float32Array(prices.flatMap((p, i) => [p, 4.5, 1, i / 5])));

  const encoder = device.createCommandEncoder();
  const cp = encoder.beginComputePass();
  cp.setPipeline(compute);
  cp.setBindGroup(0, device.createBindGroup({ layout: compute.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: books } }] }));
  cp.dispatchWorkgroups(1);
  cp.end();
  const pass = encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(),
    clearValue: [0.97, 0.96, 0.93, 1], loadOp: 'clear', storeOp: 'store' }] });
  pass.setPipeline(render);
  pass.setBindGroup(0, device.createBindGroup({ layout: render.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: books } }] }));
  pass.draw(4, 6);
  pass.end();
  device.queue.submit([encoder.finish()]);

  label('compute = BOOK_WGSL + PRICING + discount()', 12, 22, 12.5, '#1f4f8a', 'ui-monospace, monospace');
  label('render  = BOOK_WGSL + SHADING + vs()/fs()', 12, 42, 12.5, '#8a3a1a', 'ui-monospace, monospace');
  label('Heights: salePrice(price, 15) from PRICING; colours: coverColor() from SHADING', 12, 64, 12, '#444');
  prices.forEach((p, i) => label(`$${(Math.round(p * 85) / 100).toFixed(2)}`, 57 + i * 90, 262, 11.5, '#333', undefined, 'center'));
  if (err) {
    label(`Buggy main: "${err.message}"`.slice(0, 90), 12, 294, 11.5, '#8a2b2b');
    label(`reported at line ${err.lineNum} of the combined string = line ${err.lineNum - prefixLines} of main (prefix: ${prefixLines} lines)`, 12, 314, 11.5, '#8a2b2b');
  }
}
main();
</script>