Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Last active March 14, 2022 17:53
Show Gist options
  • Save cecilemuller/0be98dcbb0c7efff64762919ca486a59 to your computer and use it in GitHub Desktop.
Save cecilemuller/0be98dcbb0c7efff64762919ca486a59 to your computer and use it in GitHub Desktop.
Using Three.js "examples" (e.g. OrbitControls) with Webpack 2

Javascript files from the examples folder (such as OrbitControls) are not CommonJS or ES Modules, but they can still be used in Webpack bundles:

In package.json:

"dependencies": {
	"three": "0.84.0",
	"webpack": "2.4.1"
}

In webpack.config.js:

resolve: {
	alias: {
		'three/OrbitControls': path.join(__dirname, 'node_modules/three/examples/js/controls/OrbitControls.js'),
		'three/OBJLoader': path.join(__dirname, 'node_modules/three/examples/js/loaders/OBJLoader.js')
		// ...
	}
},

//...

plugins:[
	new webpack.ProvidePlugin({
		'THREE': 'three'
	}),
	//...
]

In application.js (CommonJS version):

require('three');
require('three/OrbitControls');
/* global THREE */

console.log(THREE.OrbitControls);

In application.js (ES Modules version):

import 'three';
import 'three/OrbitControls';
/* global THREE */

console.log(THREE.OrbitControls);
@cyrillegin
Copy link

cyrillegin commented Dec 27, 2017

Just a side note in case anyone else was having trouble, I needed to use import 'three/examples/js/loaders/OrbitControls';. The rest was perfect though, thanks!

@doommm
Copy link

doommm commented Jun 6, 2018

Having the same trouble , and get it done in another way:
In webpack.config.js

resolve: {
    alias: {
      three$: 'three/build/three.min.js',
      'three/.*$': 'three',
       // don't need to register alias for every module
    },
    // ...
},
plugins: [
    new webpack.ProvidePlugin({
      THREE: 'three',
      // ...
    }),
    // ...
],

Then just do import 'three/examples/js/controls/OrbitControls'; directly in JS, everything works fine.

@jbownzino
Copy link

thank you!

@casamia918
Copy link

Thank you! I really appreciated with it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment