Rollup build setup to import glsl files and three.js examples

###Basic Setup

Next, I use three.js as a node module - this isn’t neccessary, but you might have to change things a little if you are including it some other way:

npm install --save three

A simple main file will then be:

//main.js
import * as THREE from 'three';

// other imports

// rest of your code

Importing example files as modules

If we want to import an example, say OrbitControls, we will have to make some minor changes to the file. First, we will need to add

import * as THREE from 'three';

to the top of the file to make the namespace available. Unfortunately though, the imported THREE namespace is not modifiable, so the next line,

THREE.OrbitControls = function ( object, domElement ) {

will cause an error. We’ll change it to:

export default function OrbitControls ( object, domElement ) {

The full modified file is here (only two lines changed)

Now we can import OrbitControls in main.js:

//main.js
import * as THREE from 'three';

import OrbitControls from '../controls/OrbitControls.module.js';

// other imports

// setup code

const controls = new OrbitControls( camera, renderer.domElement );

// rest of your code

I’ve tested this pattern with a couple of the example files, some may need more work though.

2 Likes