Best practice modules with global

Hi,

I am rewriting my threejs code to use the modules

For example i am now doing the following to import threejs and some modules I need.

<script type="module">
import * as THREE from '../three/build/three.module.js';          
import { OrbitControls } from '../three/examples/jsm/controls/OrbitControls.js';
import { OBJLoader } from '../three/examples/jsm/loaders/OBJLoader.js';
import { MTLLoader } from '../three/examples/jsm/loaders/MTLLoader.js';
import { OBJExporter } from '../three/examples/jsm/exporters/OBJExporter.js';
 </script>

Now I have a myfile.js file that I created that is not a module. How do I tell this file what the variable THREE is? I used to load three like this in the main index.html file

<script src="../js/three.min.97.js"></script>
<script src="../js/myfile.js"></script>

for example how do I get my myfile.js file to recognize 'THREE"

var scene = new THREE.Scene();

Thanks in advance

You have to make sure that your code runs inside the <script type="module"> tag. Have you tried to just copy the contents of myfile.js and put it beneath the ES6 import statements?

OK so I pasted a small part of the file into just below ES6 import statements and it seemed to be OK - no errors anyway!

So how do I include this file without having to paste everything into the one file below the imports? Any ideas?

Thanks

You probably need to refactor your code so myfile.js becomes a module itself. Meaning the above imports are moved from the HTML file in myfile.js. You can then use some sort of start or init routine than you can call in index.html. So something like:

<script type="module">       
import { App } from './myfile.js';

App.start();
 </script>

Or you trying to use a build tool to produce an app bundle (which is then included in index.html).

OK - I had a feeling that was what you might say. In fairness it’s a better way to write the code so i’ll bit the bullet and try and get it working.

Thanks again for the help

1 Like

You can also export globals from a module with window.THREE = THREE. I don’t really recommend that, it can break as soon as you bring in any external three.js libraries as described in ES6 modules + other THREE libraries. Using modules consistently works, or a simple bundler like Parcel can be helpful.