BuildingJarl BuildingJarl - 1 year ago 134
Javascript Question

How do i import additional plugins for an already imported library using JSPM?

I successfully imported a js 3d rendering libary with JSPM like so:

import THREE from 'three.js/build/three';

I would also like to import the orbit controls plugin for Three.js

import OrbitControls from 'three.js/examples/js/controls/OrbitControls';

but this throws an error since the plugin has no reference to the library

Uncaught ReferenceError: THREE is not definedOrbitControls.js:24 (anonymous function)system.src.js:2187 doEvalsystem.src.js:2153 __evalsystem.src.js:212 asystem.src.js:1019 global.e.metadata.format.e.metadata.executesystem.src.js:540 csystem.src.js:403 ssystem.src.js:715 executees6-module-loader.src.js:1879 oes6-module-loader.src.js:1927 pes6-module-loader.src.js:1701 jes6-module-loader.src.js:1749 kes6-module-loader.src.js:1575 (anonymous function)es6-module-loader.src.js:1177 Oes6-module-loader.src.js:1136 Kes6-module-loader.src.js:927 y.whenes6-module-loader.src.js:818 v.runes6-module-loader.src.js:97 a._draines6-module-loader.src.js:62 draines6-module-loader.src.js:267 b
es6-module-loader.src.js:139 Potentially unhandled rejection [2] Error loading "github:mrdoob/three.js@master/examples/js/controls/OrbitControls" at http://localhost:8080/jspm_packages/github/mrdoob/three.js@master/examples/js/controls/OrbitControls.js
Error loading "github:mrdoob/three.js@master/examples/js/controls/OrbitControls" from "app/main" at http://localhost:8080/app/main.js
Error evaluating http://localhost:8080/jspm_packages/github/mrdoob/three.js@master/examples/js/controls/OrbitControls.js
Uncaught ReferenceError: THREE is not defined (WARNING: non-Error used)

The plugin adds more functionality to the library like so:

THREE.OrbitControls = function ( object, domElement ) { ... }

What is the correct way to import the plugin?

Answer Source

In this example THREE is initialized in its own module scope (ModuleEnvironment, read here), not global scope, and it's not being exported. The problem is OrbitControls is looking for THREE in its module scope and then in the global scope. So TREE is not found and error is thrown.

What you can do with it:

  1. If you're writing code for browsers - you can just not use es6 module system for libraries which does not support it. Just load them through the script tags and use as global variables (as always, before es6).

  2. You can use system.js. In that case you must configure your System something like:['TREE'] = 'three.js/build/three';
    System.meta['three.js/build/three'] = { format: 'global', exports: 'jQuery' };
    System.meta['three.js/examples/js/controls/OrbitControls'] = { deps: 'TREE' }

    Then you can import these modules like:

    import THREE from 'THREE';
    import 'three.js/examples/js/controls/OrbitControls';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download