UNPKG

1.61 kBJavaScriptView Raw
1const Asset = require('../Asset');
2const localRequire = require('../utils/localRequire');
3const path = require('path');
4const {promisify} = require('@parcel/utils');
5const Resolver = require('../Resolver');
6
7class GLSLAsset extends Asset {
8 constructor(name, options) {
9 super(name, options);
10 this.type = 'js';
11 }
12
13 async parse() {
14 const glslifyDeps = await localRequire('glslify-deps', this.name);
15
16 // Use the Parcel resolver rather than the default glslify one.
17 // This adds support for parcel features like aliases, and tilde paths.
18 const resolver = new Resolver({
19 extensions: ['.glsl', '.vert', '.frag'],
20 rootDir: this.options.rootDir
21 });
22
23 // Parse and collect dependencies with glslify-deps
24 let cwd = path.dirname(this.name);
25 let depper = glslifyDeps({
26 cwd,
27 resolve: async (target, opts, next) => {
28 try {
29 let res = await resolver.resolve(
30 target,
31 path.join(opts.basedir, 'index')
32 );
33 next(null, res.path);
34 } catch (err) {
35 next(err);
36 }
37 }
38 });
39
40 return promisify(depper.inline.bind(depper))(this.contents, cwd);
41 }
42
43 collectDependencies() {
44 for (let dep of this.ast) {
45 if (!dep.entry) {
46 this.addDependency(dep.file, {includedInParent: true});
47 }
48 }
49 }
50
51 async generate() {
52 // Generate the bundled glsl file
53 const glslifyBundle = await localRequire('glslify-bundle', this.name);
54 let glsl = glslifyBundle(this.ast);
55
56 return `module.exports=${JSON.stringify(glsl)};`;
57 }
58}
59
60module.exports = GLSLAsset;