-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathrollup-shader-chunks.mjs
49 lines (43 loc) · 1.54 KB
/
rollup-shader-chunks.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { createFilter } from '@rollup/pluginutils';
/** @typedef {import('rollup').Plugin} Plugin */
/** @typedef {string | string[]} GlobPattern */
/**
* @typedef {Object | null} PluginOptions
* @property {GlobPattern?} include - pattern(s array) to import
* @property {GlobPattern?} exclude - pattern(s array) to ignore
* @property {boolean?} enabled - enable the plugin
*/
/**
* @type {readonly string[]}
*/
const DEFAULT_SHADERS = Object.freeze(['**/*.js']);
/**
* @param {PluginOptions} options - Plugin config object
* @returns {Plugin} The plugin that converts shader code.
*/
export function shaderChunks({
include = DEFAULT_SHADERS,
exclude = undefined
} = {}) {
const filter = createFilter(include, exclude);
return {
name: 'shaderChunks',
transform(source, shader) {
if (!filter(shader)) return;
source = source.replace(/\/\* *glsl *\*\/\s*(`.*?`)/gs, (match, glsl) => {
return glsl
.trim() // trim whitespace
.replace(/\r/g, '') // Remove carriage returns
.replace(/ {4}/g, '\t') // 4 spaces to tabs
.replace(/[ \t]*\/\/.*/g, '') // remove single line comments
.replace(/[ \t]*\/\*[\s\S]*?\*\//g, '') // remove multi line comments
.concat('\n') // ensure final new line
.replace(/\n{2,}/g, '\n'); // condense 2 or more empty lines to 1
});
return {
code: source,
map: null
};
}
};
}